Sign in to unlock all code snippets and resources
100% tested and verified code snippets
New here? Register for free to get started
© Copyright – 2024 – All Rights Reserved. Created by SuperWP
Do you have products on your WooCommerce store that aren’t quite ready for purchase yet? Maybe you’re offering a pre-order, waiting for new stock to arrive, or simply want to showcase a product without the immediate “buy now” pressure. Whatever the reason, WooCommerce doesn’t offer a built-in way to hide the “Add to Cart” button on specific products.
This blog post will guide you through a code snippet that adds a handy checkbox to your product editing screen. By checking this box, you can easily disable the “Add to Cart” button for individual products or variations, giving you more control over your store’s functionality.
Here’s what you’ll learn:
Understanding the Code
The provided code tackles this functionality through three key functions:
Adding the Checkbox:
action_woocommerce_product_options_inventory_product_data()
: This function injects a checkbox into the product editing screen. The checkbox, named “_prevent_add_to_cart_button”, comes with a customizable label (“My Label”) and description (“Prevent add to cart”).Saving the Checkbox Selection:
action_woocommerce_admin_process_product_object()
: This function handles what happens when you save the product. It checks if the checkbox was selected and stores the selection (“yes” for checked, “no” for unchecked) as custom meta data for the product.Controlling “Add to Cart” Behavior:
filter_woocommerce_is_purchasable()
: This function acts as the gatekeeper for the “Add to Cart” button. It retrieves the saved meta data value (“_prevent_add_to_cart_button”). If the value is “yes” (indicating the checkbox was selected), the function sets the product’s purchasable status to “false,” effectively hiding the “Add to Cart” button.filter_woocommerce_variation_is_purchasable()
: This function tackles variable products. It retrieves the meta data value from the parent product, as variations inherit some attributes. Similar to the first function, it hides the button if the meta data indicates the button should be prevented.Putting it All Together
By working in conjunction, these functions grant you the ability to designate specific products (or their parent products in case of variations) as unpurchasable. This can be useful for various scenarios, such as:
By implementing this code snippet, you gain more control over your WooCommerce product display. You can now easily hide the “Add to Cart” button on specific products, giving you the flexibility to manage your inventory and customer experience more effectively.
Stay UpTo Date with Latest Post And news: