首页 > 解决方案 > 当产品“缺货”时,Woocommerce 将属性“Stockstatus”设置为“已售出”

问题描述

我在页面上使用简码块来显示艺术家在我们的主页和艺术家的画廊页面上出售和已售出的艺术品。例如:

  1. 在首页 [products limit="8" columns="4" orderby="id" order="DESC" visibility="visible" attribute="stockstatus" terms="sold" terms_operator="NOT IN"]
  2. 在艺术家画廊页面 [products limit="8" columns="4" orderby="id" order="DESC" visibility="visible" attribute="stockstatus" terms="sold" terms_operator="NOT IN" tag=" "]

(terms_operator 设置为“IN”以显示已售商品)

我想展示已售出和待售的艺术品,以表明艺术家的受欢迎程度。

我使用了属性,因为我找不到使用产品库存状态来做同样事情的方法。因此,当一件艺术品的库存为 0(Out of Stock)时,它仍然会显示在“待售清单”中,而不是“已售出清单”中。

我正在尝试自动将缺货的艺术品移到艺术家的已售出列表中,而不必每次都手动将“stockstatus”属性设置为“已售出”。

所以我要么需要帮助:a)更改简码 b)修复下面我尝试编写的代码片段(基于 Stackoverflow 上的早期问题)但失败并出现错误:

add_action('woocommerce_product_is_in_stock', 'update_stockstatus_attribute');
function update_stockstatus_attribute() {
        
    if (!$product->is_in_stock())
    {
            // Your product attribute settings
            $taxonomy   = 'Stockstatus'; // The taxonomy
            $term_name  = "Sold"; // The term

            $attributes = (array) $_product->get_attributes();
            $term_id    = get_term_by( 'name', $term_name, $taxonomy )->term_id;

            // 1) If The product attribute is set for the product
            if( array_key_exists( $taxonomy, $attributes ) ) {
                foreach( $attributes as $key => $attribute ){
                    if( $key == $taxonomy ){
                        $attribute->set_options( array( $term_id ) );
                        $attributes[$key] = $attribute;
                        break;
                    }
                }
            $_product->set_attributes( $attributes );
            }
            // 2. The product attribute is not set for the product
            else {
                $attribute = new WC_Product_Attribute();

                $attribute->set_id( sizeof( $attributes) + 1 );
                $attribute->set_name( $taxonomy );
                $attribute->set_options( array( $term_id ) );
                $attribute->set_position( sizeof( $attributes) + 1 );
                $attribute->set_visible( true );
                $attribute->set_variation( false );
                $attributes[] = $attribute;

                $_product->set_attributes( $attributes );
            }

            $_product->save();

            // Append the new term in the product
            if( ! has_term( $term_name, $taxonomy, $_product->get_id() ) )
                wp_set_object_terms($_product->get_id(), $term_slug, $taxonomy, true );
          
        }
}

提前感谢您提供的任何帮助

标签: woocommerce

解决方案


推荐阅读