在Woocommerce产品变体中隐藏“添加到购物车"按钮以获取特定的属性值 [英] Hide Add to Cart button in Woocommerce product variations for a specific attribute value

查看:264
本文介绍了在Woocommerce产品变体中隐藏“添加到购物车"按钮以获取特定的属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Woocommerce中,我试图隐藏添加到购物车"按钮以显示具有其中一个属性的特定选定值的变体.每个变体都有两个属性(pa_colorpa_size) 例如,对于可变产品,我们有以下选项:

In Woocommerce, I'm trying to hide add to cart button for variations with a specific selected value for one of attributes. There are two attributes for each variation (pa_color and pa_size) For example for a variable product, we have these options:

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

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

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

I want to hide add to cart button for XL so users could not add options having XL to cart (1 and 4 in this example)

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

P.S: We don't want to disable the variation, so variation image could show up by selecting this option, So deactivating the variation or removing the price and.. isn't the solution for us.

推荐答案

这是使产品属性"pa_size" 的产品变体添加到购物车按钮无效的方法>并带有"XL" 值:

Here is the way to make add to cart button inactive on product variations which product attribute "pa_size" with a "XL" value:

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文件中.经过测试,可以正常工作.

Code goes in function.php file of your active child theme (or theme). Tested and works.

这篇关于在Woocommerce产品变体中隐藏“添加到购物车"按钮以获取特定的属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆