Hide Add to Cart button in Woocommerce product variations for a specific attribute value

前端 未结 2 1318
攒了一身酷
攒了一身酷 2020-12-21 18:08

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 (

相关标签:
2条回答
  • 2020-12-21 18:16

    Use your slug text for 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;
    }

    0 讨论(0)
  • 2020-12-21 18:32

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

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

    0 讨论(0)
提交回复
热议问题