0
votes

I'm trying to hide the "add to cart" button for all products except for one or two items on my woocommerce website.

Here is a simple solution I found that sets the products to "purchasable = false". After placing in the function.php file all the "add to cart" buttons disappear.

/** hides add to cart button**/

add_filter( 'woocommerce_is_purchasable', false );

How do I add exception to this?

I would like to show the add to cart button for product ids 22 & 23

I have spent a few hours researching any help would be greatly appreciated.

1

1 Answers

0
votes

Remove the first filter:

/** REMOVE **/

// add_filter( 'woocommerce_is_purchasable', false );

The woocommerce_is_purchasable filter takes in the default value of $is_purchasable (boolean) and the WC_Product $object it is parsing. So check each object and return true to show the button and false to hide it.

add_filter('woocommerce_is_purchasable', 'myplugin_is_purchasable', 10, 2);

function myplugin_is_purchasable( $is_purchasable, $object ) {
    // Checks to see if the product id is 22 or 23, 
    // returns true if is, false otherwise.  
    return ( 22 === $object->id || 23 === $object->id );
}

NOTE: This is probably not a very good way to accomplish this. It shouldn't be hardcoded. If the id's of the products you want to show change, it will be transparent to the user later on. You will have to dive back into code to change it. It's just generally not a good idea to hard code id's like this.