I have a snipped below that restricts woocommerce orders to 5 items. When they try go through checkout with more than 5 items it pops up a message telling them that and they then have to remove items. What I am wondering is if there is a way so that they can’t add more than 5 items to the basket?
add_action( 'woocommerce_check_cart_items', 'set_max_num_products' );
function set_max_num_products() {
// Only run in the Cart or Checkout pages
if( is_cart() || is_checkout() ) {
global $woocommerce;
// Set the max number of products before checking out
$max_num_products = 5;
// Get the Cart's total number of products
$cart_num_products = WC()->cart->cart_contents_count;
// A max of 5 products is required before checking out.
if( $cart_num_products > $max_num_products ) {
// Display our error message
wc_add_notice( sprintf( '<strong>A maxiumum of %s samples are allowed per order. Your cart currently contains %s.</strong>',
$max_num_products,
$cart_num_products ),
'error' );
}
}
}
Every product must be validated before it can be added to the cart. You can modify the validation status via the
woocommerce_add_to_cart_validation
filter and thus control whether it is or is not added to the cart.