在 WooCommerce 中,如果我的产品只有一个可用选项,我需要预先选择它。
我尝试过:
add_filter('woocommerce_dropdown_variation_attribute_options_args', 'fun_select_default_option', 10, 1);
function fun_select_default_option($args) {
if (count($args['options']) === 1) {
$onlyOption = reset($args['options']);
if (!isset($onlyOption['disabled']) || !$onlyOption['disabled']) {
$args['selected'] = $onlyOption;
}
}
return $args;
}
如果下拉菜单只有一个选项并且该选项可用,则此方法有效。但如果有 3 个和 1 个可用则不然。
所以我尝试过滤掉可用的选项,但仍然不起作用:
add_filter('woocommerce_dropdown_variation_attribute_options_args', 'fun_select_default_option', 10, 1);
function fun_select_default_option($args) {
$selectableOptions = array_filter($args['options'], function($option) {
return !isset($option['disabled']) || !$option['disabled'];
});
if (count($selectableOptions) === 1) {
$onlyOption = reset($selectableOptions);
$args['selected'] = $onlyOption;
}
return $args;
}
如果只有一个属性选项可用,则应预先选择。
要自动定义可变产品的默认变体属性,您可以使用以下命令:
add_filter( 'woocommerce_product_get_default_attributes', 'auto_define_default_variation_attributes', 10, 2 );
function auto_define_default_variation_attributes( $default_attributes, $product ){
// Loop through available variations
foreach( $product->get_available_variations('objects') as $variation ) {
// Target purchasable variation
if ( $variation->is_purchasable() ) {
// Loop through attributes for the current variation
foreach( $variation->get_attributes() as $attribute => $value ) {
if ( ! empty($value) ) {
$default_attributes[$attribute] = $value;
} else {
// If there is no defined value, set it
$_attributes = $product->get_variation_attributes();
$default_attributes[$attribute] = current($_attributes[wc_attribute_label($attribute, $product)]);
}
}
break; // Stop the loop
}
}
return $default_attributes;
}
代码位于子主题的functions.php 文件中(或插件中)。已测试并有效。