Remove Add to Cart Button for Specific Products

Recently I was working on a project where I had to remove the "Add to Cart" button for certain products. Setting up the stock to be "0" was not an option as the potential customer might think that the item is out of stock. Instead, the business owner wanted to display the price with a message "In Store Purchase Only". Now adding message was not the big issue rather removing the "add to cart" button for few specific product was the main challenge.

I spent few minutes searching for some kind of hooks related with the add to cart button and eventually I found something to get my job done. Here is the snippet.

add_action('woocommerce_before_single_product','non_purchasable_products');
function non_purchasable_products(){
   global $post;
   // current product id
   $id = $post->ID;
   // product ids
   $pids = array(33,115,117);
   foreach ($pids as $pid){
      if ($pid == $id){
         remove_action('woocommerce_single_product_summary','woocommerce_template_single_add_to_cart', 30);
      }
   }
}

In order disable the add to cart button for a very specific product, I wrote a custom function which has been hooked with an WooCommerce action function that gets called before the template for the product renders. Using my custom function, the first thing I had to do is to grab the ID number of the post/product that is going to be displayed. I declared $pids variable to hold the post IDs. These are the posts/products where I don't want to display the "Add to Cart" button.

Using a simple foreach loop, I checked every single values(array) on $pids whether it matches with the current post ID or not. If it does match, a "remove_action" function will be called to remove the add to cart button for that post. This is as simple as it can get. I hope you would find this post to be useful.

Note: This snippet will not remove the "Add to Cart" button on product archive page based on their ID number. So, basically you may find this snippet little less useful. However, I wrote a post way back explaining how to remove "Add to Cart" button from product archive pages altogether. Using that snippet along with this one could be useful for many.

References: foreach loop, WooCommerce Hooks

Related

Comments

Comments list