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 );

Leave a Reply

Privacy & more..

Cookie Consent Policy