Loading...

I wanted to make sure products in a certain product category could only have a maximum of two products added to the cart. I used the woocommerce_add_to_cart_validation hook to run the function below which checks how many products the user has selected and what category those products are in if there are more than 2 of the product selected.

If the function returns true the item will successfully add to cart. We add the error message with the wc_add_notice() function and set the return value to false, preventing the items being added to the cart.

In order to make this bulletproof you will need to add a similar test to the update cart process as well.
Hint: woocommerce_update_cart_validation.

/*
|  PREVENT TOO MANY PRODUCTS BEING ADDED TO CART
*/ 
function custom_max_sample_quantity_validation($status, $product_id, $quantity, $variation_id, $variations){
	if($quantity >= 3 && has_term('samples','product_cat', $product_id)) {
		wc_add_notice('maximum 2 of these products allowed per order','error');
		$status = false;
	} 
	
	return $status;	
}
add_action( 'woocommerce_add_to_cart_validation', 'custom_max_sample_quantity_validation', 1, 5 );

Latest Posts

Portfolio

Contact

Fill in the form below to send us a message. Your details will not be used for promotional purposes or passed on to any third parties.

 

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close