skip to Main Content

I have the following code to disable the add-to-cart button for products not in certain categories. However only the first category in the array is being respected.

If I have 5 categories – hats, shirts, shoes, sneakers, backpacks – It should match all of them except sneakers and backpacks. But it’s only working for sneakers (the first in the array) – backpacks also gets the add-to-cart button disabled.

 function remove_add_to_cart_buttons() {
    // remove add-to-cart button if product is not in category "sneakers" or "backpacks"
  if( ! has_term( array( 'sneakers', 'backpacks' ), 'product_cat' ) ) {
    remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart');
    remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart');
  }
}
add_filter('woocommerce_is_purchasable', 'remove_add_to_cart_buttons', 10, 2);

Not sure what I am doing wrong but everything I’ve tried doesn’t make any difference :/

References:

Also tried:

if( ! is_product_category( array( 'sneakers', 'backpacks'))) { but this disabled ALL add-to-cart buttons.

2

Answers


  1. Chosen as BEST ANSWER

    Using the second example here: https://stackoverflow.com/a/53058011/5204226 works (I had to change has_terms to has_term).

    function conditional_purchasable_products( $is_purchasable, $product ) {
        // HERE your product categories (can be IDs, slugs or names terms)
        $terms = array( 'sneakers', 'backpacks');
    
        $product_id = $product->get_id(); // The product ID
    
        if( ! has_term( $terms, 'product_cat', $product_id ) ){
            $is_purchasable = false;
        }
    
        return $is_purchasable;
    }
    add_filter('woocommerce_is_purchasable','conditional_purchasable_products', 20, 2);
    

    • you must return a $value, so return is missing
    • woocommerce_is_purchasable has 2 parameters, $value & $product. however, these are empty in your code

    Give it a try this way

    function remove_add_to_cart_buttons( $value, $product ) {
        // remove add-to-cart button if product is not in category "sneakers" or "backpacks"
        if( ! has_term( array( 'sneakers', 'backpacks' ), 'product_cat' ) ) {
            $value = false;
        }
    
        return $value;
    }
    add_filter('woocommerce_is_purchasable', 'remove_add_to_cart_buttons', 10, 2 );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search