woocommerce - 当产品“缺货”时,Woocommerce 将属性“Stockstatus”设置为“已售出”
问题描述
我在页面上使用简码块来显示艺术家在我们的主页和艺术家的画廊页面上出售和已售出的艺术品。例如:
- 在首页 [products limit="8" columns="4" orderby="id" order="DESC" visibility="visible" attribute="stockstatus" terms="sold" terms_operator="NOT IN"]
- 在艺术家画廊页面 [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 );
}
}
提前感谢您提供的任何帮助
解决方案
推荐阅读
- spring - 如何从 Spring WebTestClient JSON 响应中提取值以供后续请求使用?
- vue.js - 如何为使用 VueJS 启用的开关设置默认设置?
- c++ - OpenVINO - 图像分类
- swift - 是否可以在 Catalyst 应用程序中打开另一个 MacOS 应用程序
- php - Laravel:按数组排序
- typescript - 如何创建一个只接受具有特定静态成员的类实例的泛型函数?
- jsf-2.2 - JSF Flow Scope 的使用安全性如何?
- kotlin - 映射到 ktor 后调用正文时找不到类“kotlin.collections.HashMap”
- laravel - 如何在 Laravel 8 中使用 npm 解决模块“os”和“fs”的问题?
- postman - 使用邮递员的 API 调用导致问题