【问题标题】:Auto select first available options from a variation on WooCommerce variable products从 WooCommerce 可变产品的变体中自动选择第一个可用选项
【发布时间】:2020-11-07 04:00:17
【问题描述】:

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

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

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

我尝试在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;
    
                }

            });
        
        } 

    });
    
});

【问题讨论】:

    标签: jquery wordpress woocommerce taxonomy-terms product-variations


    【解决方案1】:

    你可以使用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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-26
      • 1970-01-01
      • 2019-01-12
      • 1970-01-01
      • 2014-02-22
      • 1970-01-01
      • 2023-03-14
      • 1970-01-01
      相关资源
      最近更新 更多