Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
873 views
in Technique[技术] by (71.8m points)

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

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

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: 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...