If you just started learning WooCommerce and interested to develop Woocommerce Extensions, then you have just reached the right place.
In this tutorial, we are going to guide you on how you can use Woocommerce Hooks to conditionally add products to the cart.
What are the hooks?
Hooks in WordPress essentially allow you to change or add code without editing core files. They are used extensively throughout WordPress and WooCommerce and are very useful for developers.
However, you don’t need to have familiarity with Woocommerce Hooks to continue with this tutorial, we will guide you how you can use Woocommerce Hooks in your plugin.
We have divided this tutorial into several sections:
- Prevent Adding to the Cart will guide you to write custom rules and use a hook to prevent adding products to the cart.
- Prevent Updating Cart will guide you how you can prevent updating cart base on specific rules.
- Display Notices will guide you on how to display notice, so the customer will know why we have prevented adding a specific product to the cart or updating the cart.
Prevent Adding to the Cart
Let’s say we want that customer can add a maximum of two items for each of the products.
So we need to prevent products adding to the cart if the quantity is more than two for each of the products. Nothing to worry, WooCommerce provides a hook woocommerce_add_to_cart_validation which we can use to validate products before adding to the cart.
The following code will prevent product adding to the cart if quantity is more than two.
Quite simple, right?
We also need to check if the product is already in the cart and quantify is less than two. Update the function with the following code.
Prevent Updating Cart
In this section, we will show you how you can prevent updating cart, so when customers try to update cart they will not be able to add more than two items of each of the products.
This time we will use a different hook woocommerce_update_cart_validation to make it work. The following code will do the trick.
Great! Now we are done with validations. In the next section, we will guide you on how to display notices if the product does not pass validation.
It’s time do display appropriate notices, so customers know what’s happening and don’t get confused. Let’s do it.
We can use wc_add_notice function to store a notice and display it to the customers. Just pass appropriate message while calling the function, WooCommerce will do the rest of the trick for you.
Add to Cart Validation Notices
In the following code, we are displaying notices if the quantity is more than two or total quantity including cart items is more than two.
Update Cart Validation Notices
In the following code, we are displaying the notice if the quantity is more than two.
Finally, we have done it. You are not limited to add conditions while working with validations. So try to play with your conditions.
If you liked this tutorial, don’t forget to spread the word.