我有一款 T 恤产品,可以选择尺寸和颜色。选择一个变体后,我希望在另一个变体中自动选择第一个可用选项。
例如,如果我有一件只有大号和超大号的白色 T 恤和一件只有小号和中号的绿色 T 恤,当用户选择白色时,它应该自动选择大号。但是,如果用户随后改变主意并选择绿色,则应自动选择小。但是,只有在其他变体中没有选择已经可用的选项时,才会发生这种情况。
虽然我可以运行脚本来选择第一个启用的更改选项,但一旦用户再次更改为不同的颜色,WooCommerce 就会发出“缺货”警告并清除他们的选择,然后我才能再次运行更改脚本。
我试图在 woocommerce_variation_select_change
上运行, woocommerce_variation_has_changed
和 show_variation
hide_variation
没有任何运气。
任何帮助将非常感激。以下是我到目前为止所想出的大致内容:
$(document).on( 'change', '.variations select', function( event ) {
if ( !$(this).val() ) return false;
var select = $(this);
var variations = $(this).closest('.variations');
$(variations).find('select').not(select).each(function() {
var val = $(this).val();
if ( !val || ( val && !$(this).find('option[value='+val+']:enabled') ) ) {
$(this).find('option:enabled').each(function() {
if ( $(this).attr('value') ) {
$(this).prop('selected', 'selected');
return false;
}
});
}
});
});
最佳答案
您可以使用 functions.php
来解决此问题。而不是在客户端编写js。
add_filter('woocommerce_dropdown_variation_attribute_options_args','fun_select_default_option',10,1);
function fun_select_default_option( $args)
{
if(count($args['options']) > 0) //Check the count of available options in dropdown
$args['selected'] = $args['options'][0];
return $args;
}
注意:答案复制自 Wordpress StackExchange
关于jquery - 从 WooCommerce 可变产品的变体中自动选择第一个可用选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62952394/