Hide Add to Cart in WooCommerce for variations with specific attribute value

39 Views Asked by At

In WooCommerce, I would like add to cart button to be disabled if a certain attribute value is selected. The attribute taxonomy is "pa_badge-print" and the term slug value is "yes"

I have used this code:

add_filter( 'woocommerce_variation_is_purchasable', 'conditional_variation_is_purchasable', 20, 2 );
function conditional_variation_is_purchasable( $purchasable, $product ) {

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

    $taxonomy  = 'pa_badge-print';
    $term_slug =  'yes';

    ## ---- The active code ---- ##

    // Check if the product has attributes
    if ( $product->get_attributes() ) {
        // Loop through all product attributes in the variation
        foreach ( $product->get_variation_attributes() as $variation_attribute => $term_slug ){
            // Get the attribute taxonomy
            $attribute_taxonomy = str_replace('attribute_', '', $variation_attribute);
            // Get the term object by slug
            $term = get_term_by( 'slug', $term_slug, $attribute_taxonomy );
            // Check if the term exists and its slug is "yes"
            if ( $term && $term->slug === $term_slug ) {
                $purchasable = false; // Disable purchasable
                break; // Exit the loop
            }
        }
    }

    return $purchasable;
}

And currently it disables add to cart on all attribute values. So for example, if the attribute value was "no", the add to cart should still show.

This is a screen shot of the product with the values no selected. The add to cart button should show with no values selected; enter image description here

1

There are 1 best solutions below

2
LoicTheAztec On

There are 2 ways to hide add to cart for variations that have a specific attribute value:

1st Way:

add_filter( 'woocommerce_available_variation', 'hide_add_to_cart_for_specific_attribute_value', 10, 3);
function hide_add_to_cart_for_specific_attribute_value( $data, $product, $variation ) {
    $attributes = $variation->get_attributes();
    $taxonomy   = 'pa_badge-print';

    if ( isset($attributes[$taxonomy]) && $attributes[$taxonomy] === 'yes' ) {
        $data['is_purchasable'] = false;
    }
    return $data;
}

2nd way:

add_filter( 'woocommerce_variation_is_purchasable', 'hide_add_to_cart_for_specific_attribute_value', 10, 2 );
function hide_add_to_cart_for_specific_attribute_value( $is_purchasable, $variation ) {
    $attributes = $variation->get_attributes();
    $taxonomy   = 'pa_badge-print';
    
    if ( isset($attributes[$taxonomy]) && $attributes[$taxonomy] === 'yes' ) {
        $is_purchasable = false;
    }
    return $is_purchasable;
}

Code goes in functions.php file of your active child theme (or active theme). Both ways work.