根据类别获取活动的产品类别并更改SAME产品的默认差异值woocommerce
我正在根据他的类别工作,显示SAME产品的默认差异值。 例如,我出售一张带蓝色选项&红色的卡。 当用户来自类别ONE时,我希望默认值为蓝色。 如果他来自TWO类别,则该值为红色。根据类别获取活动的产品类别并更改SAME产品的默认差异值woocommerce
我找到一个带有“woocommerce_product_default_attributes
”元素的钩子,但我不知道如何使用它。
注:看来即使你的产品有两种类别
例是woocommerce识别每个产品只有一类(编辑):
我有一个产品P
。
产品P
分为两类:Cat 1
& Cat 2
。
此外,产品P
有两个变量:Blue
& Red
当用户来到由Cat 1
,我想要的默认值是Blue
。 如果他来了Cat 2
,值将是Red
。
@LoicTheAztech(下同)作品的答案代码,但是:
当我去
Cat 1
或Cat 2
,我可以看到,对于Woocommerce,该产品仅在Cat 1
,甚至如果我们可以通过这两个类别访问。
所以在这之前,我需要解决woocommerce问题。
在WooCommerce 3+过滤器钩
woocommerce_product_default_attributes
位于get_variation_default_attributes()
的方法已过时,所以它不是真正的权利挂钩,实现你想要什么。
get_variation_default_attributes()
方法被替换为get_default_attributes()
。
你可以实现你的条件函数在woocommerce_before_add_to_cart_form
行动挂钩,例如。
注:
- 产品属性分类总是“PA_” +属性蛞蝓
- 您需要设置在变型产品的默认值的变化选项卡这个属性开始设置。
代码:
add_action('woocommerce_before_add_to_cart_form', function(){
global $product;
// We EXIT if it's not a variable product
if(! $product->is_type('variable')) return;
## DEFINE HERE the desired product attribute taxonomy
$pa_attribute = 'pa_color';
$default_attribute_for_variation = $product->get_variation_default_attribute($pa_attribute);
// We EXIT if Product Attribute Color is not set as variation usage
if(empty($default_attribute_for_variation)) return;
// Get the array of default attributes
$default_attributes = $product->get_default_attributes();
// For product category 'ONE => Attribute "blue" slug value
if(has_term('clothing', 'product_cat', $product->get_id()))
$default_attributes[$pa_attribute] = 'blue';
// For product category 'TWO' => Attribute "blue" slug value
elseif(has_term('TWO', 'product_cat', $product->get_id()))
$default_attributes[$pa_attribute] = 'red';
else return; // If no product categories match we exit
// If a product category match we set the default attribute
$product->set_default_attributes($default_attributes);
}, 80, 0);
代码放在您的活动子主题(或主题)的function.php文件或也以任何插件文件。
此代码已经过测试并可正常工作。
嗨@LoicTheAztec,对于最近的答案感到抱歉,并感谢您的帮助!我看到了你的代码,但我意识到一件事:Woocommerce不允许两种类型的同一产品。事实上,SAME产品分为两类。当我尝试你的代码时,产品只能在一个.. – Efbi
@Efbi这是正常的,因为不可能为同一产品设置2个不同的默认属性值...因此,如果您的产品具有类别'ONE'和'TWO'它只适用于一个...因此,可能你必须更新你的问题,因为它不够明确。 – LoicTheAztec
我更新了我的问题,是否更清楚? – Efbi