从 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 方法时,可以使用基于对象类型和方法名称的动态挂钩 (主要用于前端:"查看”上下文)…
见this line$value = apply_filters( $this->get_hook_prefix() . $prop, $value, $this );
和this linereturn 'woocommerce_' . $this->object_type . '_get_'; 在
所以过滤器钩子是动态制作的这样(其中$this->object_type等于'product'):
'woocommerce_' . $this->object_type . '_get_' . 'default_attributes'
有 2 个参数:
-
$attributes(替换$value的属性值)
-
$product(替换$this的类实例对象)…
查看Woocommerce Github closed and solved issue