从 Woocommerce 3 开始,您可以使用woocommerce_product_get_default_attributes
过滤器挂钩...因此您的 2 个产品类别的代码将如下所示:
add_filter( 'woocommerce_product_get_default_attributes', 'filtering_product_get_default_attributes', 10, 2 );
function filtering_product_get_default_attributes( $default_attributes, $product ){
// We EXIT if it's not a variable product
if( ! $product->is_type('variable') ) return $default_attributes;
## --- YOUR SETTINGS (below) --- ##
// The desired product attribute taxonomy (always start with "pa_")
$taxonomy = 'pa_color';
$category1 = 'one' // The 1st product category (can be an ID, a slug or a name)
$value1 = 'blue' // The corresponding desired attribute slug value for $category1
$category2 = 'two' // The 2nd product category (can be an ID, a slug or a name)
$value2 = 'red' // The corresponding desired attribute slug value for $category2
## --- The code --- ##
// Get the default attribute used for variations for the defined taxonomy
$default_attribute = $product->get_variation_default_attribute( $taxonomy );
// We EXIT if define Product Attribute is not set for variation usage
if( empty( $default_attribute ) ) return $default_attributes;
// For product category slug 'one' => attribute slug value "blue"
if( has_term( 'one', 'product_cat', $product->get_id() ) )
$default_attributes[$taxonomy] = 'blue';
// For product category slug 'two' => attribute slug value "red"
elseif( has_term( 'two', 'product_cat', $product->get_id() ) )
$default_attributes[$taxonomy] = 'red';
else return $default_attributes; // If no product categories match we exit
return $default_attributes; // Always return the values in a filter hook
}
代码位于活动子主题(或活动主题)的 function.php 文件中。尚未测试,但应该可以工作。
说明:
自从 Woocommerce 3 和新引入的 CRUDS setter 方法以来,当方法使用get_prop()
WC_Data
方法,可以使用基于对象类型和方法名称的动态钩子(本质上对于前端:“查看”上下文)…
See 这条线 https://github.com/woocommerce/woocommerce/blob/b2e4052e3bcc87dd100e70d25f59dc76c413f2a3/includes/abstracts/abstract-wc-data.php#L600-L623 $value = apply_filters( $this->get_hook_prefix() . $prop, $value, $this );
in
and 这条线 https://github.com/woocommerce/woocommerce/blob/b2e4052e3bcc87dd100e70d25f59dc76c413f2a3/includes/abstracts/abstract-wc-data.php#L590-L598return 'woocommerce_' . $this->object_type . '_get_';
in
So 过滤器钩子是动态制作的这边走(where $this->object_type
等于'product'
):
'woocommerce_' . $this->object_type . '_get_' . 'default_attributes'
有 2 个参数:
-
$attributes
(替换的属性值$value
)
-
$product
(替换的类实例对象$this
)…
看到它Woocommerce Github 关闭并解决了问题 https://github.com/woocommerce/woocommerce/issues/19814