Introduction
- In this tutorial, you will learn how to control the quantity of the specific set of products based on a logical condition
- Here in this tutorial, we considered the condition if the discounted product added more than our defined quantity it will notify/alert the end-user but once you understand the concept the same can be applied in different scenarios with little modifications
- Through this process, you will learn the following from the technical/development side
woocommerce_add_to_cart_validationfilter hookwoocommerce_update_cart_validationfilter hookwc_add_noticeWooCommerce notice functionwc_get_productfunction to get product instanceget_regular_priceproduct instance methodget_sale_priceproduct instance methodgenerate_cart_idcart instance methodfind_product_in_cartcart instance methodget_cart_itemcart instance method
- Sample notice

Add to cart validation
- Line 2: we defined a named constant
MAX_QUANTITYwhere it helps how much discounted product a user can add to a cart - Line 4: we called the filter hook function
add_filterwith the tagwoocommerce_add_to_cart_validationfor the functionvalidate_discounted_prdct_qty_limitation - The filter
woocommerce_add_to_cart_validationis responsible for doing validation while adding the product to the cart - Line 19: Lets we see the inner working of the hooked function
validate_discounted_prdct_qty_limitation - The hooked function has three arguments
$passedBoolean value to pass or fail the validation$product_idan integer value which is the product id that is the primary key of that product$quantityan integer which has the intended quantity of the product
- Line 20: we call the function
wc_get_productwhere we passed our product id which returns the right product object by making using of a factory pattern classWC_Product_Factorywhich return any one of the product object typesWC_Product_Simple,WC_Product_Grouped,WC_Product_External,WC_Product_Variable, etc., - Line 22: we get the products parent id if the product doesn’t have a parent which return 0 else it returns the parent product id
- Line 23: if the product id isn’t empty (possible for variable products child product or for any custom product type) then assign the variable
$product_idwith the product’s parent id - Line 27: we call our validator function
validate_product_qtyand return it - On the shop page, when the threshold limit is crossed instead of showing the notice on shop page WooCommerce redirects to a specific product page and alerts the notice which is the default flow of the ajax add to cart functionality
Update cart validation
- Line 3: we hooked our custom function
on_update_cart_limit_qtyto the hook tagwoocommerce_update_cart_validationwhich is responsible for update cart validation - Therefore this custom function solely control the WooCommerce cart page validation and previous section we explored the hook
woocommerce_add_to_cart_validationwhich can be triggered on the shop page or product page - Line 19: the function
on_update_cart_limit_qtyis a simple one-line function which calls the validation functionvalidate_product_qty - Lets we see the arguments of this function
$passedBoolean value to pass or fail the validation$cart_item_keystring value, to be clear WooCommerce generated MD5 which is used as a key for every cart item in the cart$valuesarray value, currently updated product cart item properties$quantityint value, which has the product’s updated quantity
Show validate message
- Line 12: you may be surprised by seeing this function as earlier we saw that this function as the validation function but here it just the message notification function
- The reason for this is we abstracted our validation logic in other business logic function
is_discounted_prdct_qty_exceededso you can reuse all the function up to we discussed (including this) without modifying anything and interpolate your desired validation business logic function into the if condition or even if you’re using these functions as object-oriented methods then you can inject the validation business logic as dependency injection (DI) - This function accepts three arguments they are
$product_idint value, which holds the product’s id (Primary Key)$quantityint value, validating product quantity which can be verified against ourMAX_QUANTITYconstant$action_typestring value, a switcher key which accepts eitheraddorupdateas value depends on this value we slightly modify the quantity calculation logic in the functionis_discounted_prdct_qty_exceeded
- Line 13: here whatever argument values we received are directly passed to the validation business logic function
is_discounted_prdct_qty_exceeded - Line 15: the variable
$output_stringholds the string returned by the WordPress functionwp_sprintf - Line 21: the WooCommerce function
wc_add_noticeis used to display the validation message - If product quantity exceeded the threshold limit then we return
falseelsetrue
Validation business logic
- Lets we see about the helper function
is_discounted_prdct_qty_exceeded - Line 13: We passed the argument
$product_idto the WooCommerce functionwc_get_productwhich return theWC_Productobject, if the product exists for the given product id else, returnnullif not found and if anything wrong returnfalse - Line 14: we call the method
get_regular_priceof theWC_Productobject variable$product_objthis method is responsible to return the product’s regular price i.e. actual price - Line 15: the method
get_sale_priceis similar toget_regular_pricebut it returns the discounted price - Line 17: we called the cart instance method
generate_cart_idwhich return the unique cart id of the passed product id - Line 18: the cart instance method
find_product_in_cartreturn the cart item key if the product is in the cart else return an empty string, this method is used to find whether our product is already in the cart or not- We will use this variable in if condition while adding a product to the cart we will see the purpose of this variable later
- Line 20: this conditional logic is used to check whether our product is the discounted one or not
! empty( $sale_price )here we check whether our sale price is not empty(float) $sale_price < (float) $regular_pricehere we check if the sale price is lesser than the regular price to decide whether the product is discounted or not
- Line 23: this conditional block is executed only when we are adding the product to the cart and the same product already present in the cart
'add' === $action_typehere we checking is our action type isaddiftruemeans the next expression will be executed! empty( $find_product_in_cart )here we check if the product already in the cart- The reason for checking this condition is considering like this if the product which we are adding is already in the cart with a quantity 2 and the currently adding product quantity is 3 means we need to check the sum of both cart and added product quantity which will be 5 against our threshold value 3 instead of that if we check only added quantity with the threshold value it will pass but it’s wrong therefore we summed up both added product and cart quantity
- Line 26: fetching a particular product’s data in the cart using the cart instance method
get_cart_itemusing the cart item key which we get by passing the variable$cart_id - Line 27: the variable
$cart_itemholds an array which has all the details of a particular product in the cart, we fetching the product’s cart quantity$cart_item['quantity']and sum with the add to cart quantity finally assign the total sum to the variable$quantity - Line 30: conditional check to check whether we crossed the threshold quantity if so then return
true - Line 36: if the conditions are fails then return
falseto indicate threshold is either not reached or not applicable for this product
Conclusion
- In this tutorial, you learned how to control the quantity of the products in the cart
- You can find the full source code in the GitHub