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:
- Original tutorial I followed: https://rudrastyh.com/woocommerce/if-product-in-category.html
- https://wisdmlabs.com/blog/the-right-way-to-hide-add-to-cart-button-in-woocommerce/
Also tried:
if( ! is_product_category( array( 'sneakers', 'backpacks'))) {
but this disabled ALL add-to-cart buttons.
2
Answers
Using the second example here: https://stackoverflow.com/a/53058011/5204226 works (I had to change
has_terms
tohas_term
).return
a$value
, soreturn
is missingwoocommerce_is_purchasable
has 2 parameters,$value
&$product
. however, these are empty in your codeGive it a try this way