隐藏特定属性值

时间:2018-03-27 14:10:34

标签: php wordpress woocommerce custom-taxonomy variations

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

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

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

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

2 个答案:

答案 0 :(得分:1)

以下是对产品变体进行添加到购物车按钮非活动的方法,产品属性" pa_size" 带有&#34 ; 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文件中。经过测试和工作。

答案 1 :(得分:0)

将您的条形文字用作term_name

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->slug == $term_name ){
            $found = true;
            break;
        }
    }

    if( $found )
        $purchasable = false;

    return $purchasable;
}