4

我有一件 T 恤产品,有多种尺寸和颜色可供选择。选择一个变体后,我希望在另一个变体中自动选择第一个可用选项。

例如,如果我有一件只有大号和特大号的白色 T 恤和一件只有小号和中号的绿色 T 恤,当用户选择白色时,它应该自动选择大号。但是,如果用户随后改变主意并选择绿色,它应该自动选择小。但是,只有在其他变体中没有选择可用的选项时,才会发生这种情况。

虽然我可以运行脚本来选择第一个启用的更改选项,但一旦用户再次更改为不同的颜色,WooCommerce 会发出“缺货”警告并清除他们的选择,然后我才能再次运行更改脚本。

我试图用 on 运行woocommerce_variation_select_changewoocommerce_variation_has_changedshow_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;
    
                }

            });
        
        } 

    });
    
});
4

1 回答 1

3

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复制的

于 2020-12-13T11:07:45.553 回答