首页 文章

隐藏特定属性值的Woocommerce产品变体中的“添加到购物车”按钮

提问于
浏览
1

在Woocommerce中,我正在尝试隐藏“添加到购物车”按钮,以获取其中一个属性的特定选定值的变体 . 每个变体有两个属性( pa_colorpa_size )例如,对于变量产品,我们有以下选项:

1) Red - XL 2) Red - XXL 3) Blue - M 4) Blue - XL

我想隐藏 XL 的添加到购物车按钮,因此用户无法添加XL到购物车的选项(在此示例中为1和4)

P.S:我们不想禁用变化,因此通过选择此选项可以显示变化图像,因此停用变化或移除价格和..对我们来说不是解决方案 .

1 回答

  • 1

    以下是对产品变体进行 add to cart button inactive 的方法,产品属性 "pa_size" 的值为 "XL"

    add_filter( 'woocommerce_variation_is_purchasable', 'conditional_variation_is_purchasable', 20, 2 );
    function conditional_variation_is_purchasable( $purchasable, $product ) {
    
        ## ---- Your settings ---- ##
    
        $taxonomy  = 'pa_size';
        $term_name =  'XL';
    
        ## ---- The active code ---- ##
    
        $found = false;
    
        // Loop through all product attributes in the variation
        foreach ( $product->get_variation_attributes() as $variation_attribute => $term_slug ){
            $attribute_taxonomy = str_replace('attribute_', '', $variation_attribute); // The taxonomy
            $term = get_term_by( 'slug', $term_slug, $taxonomy ); // The WP_Term object
            // Searching for attribute 'pa_size' with value 'XL'
            if($attribute_taxonomy == $taxonomy && $term->name == $term_name ){
                $found = true;
                break;
            }
        }
    
        if( $found )
            $purchasable = false;
    
        return $purchasable;
    }
    

    代码位于活动子主题(或主题)的function.php文件中 . 经过测试和工作 .

相关问题