如果选择了特定属性,则禁止用户将其添加到购物车

时间:2019-06-21 02:57:52

标签: woocommerce

在Woocommerce中,如果选择了特定属性,我想防止用户将其添加到购物车中。

属性名称为“生产时间”,我们要禁止购买的特定值为“紧急”。

下面的代码来自此链接-Hide Add to Cart button in Woocommerce product variations for a specific attribute value

但是,它仅适用于数字。当属性是文本时,它将不起作用。

add_filter( 'woocommerce_variation_is_purchasable', 'conditional_variation_is_purchasable', 20, 2 );

function conditional_variation_is_purchasable( $purchasable, $product ) {

    ## ---- Your settings ---- ##

    $taxonomy  = 'production-time';
    $term_name =  'urgent';

    ## ---- 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;
}

0 个答案:

没有答案