Limit the Number of Items in the Cart
Stops shoppers from adding more than a set total number of items to the cart, for limited releases or stock-controlled drops.
Opens WPIDE on
Code
$wpide_max_cart_items = 10; // Largest total quantity allowed in the cart.
add_filter( 'woocommerce_add_to_cart_validation', function ( $passed, $product_id, $quantity ) use ( $wpide_max_cart_items ) {
$in_cart = WC()->cart ? WC()->cart->get_cart_contents_count() : 0;
if ( $in_cart + (int) $quantity > $wpide_max_cart_items ) {
wc_add_notice( sprintf( 'You can have up to %d items in your cart.', $wpide_max_cart_items ), 'error' );
return false;
}
return $passed;
}, 10, 3 );
add_action( 'woocommerce_check_cart_items', function () use ( $wpide_max_cart_items ) {
if ( WC()->cart->get_cart_contents_count() > $wpide_max_cart_items ) {
wc_add_notice( sprintf( 'Your cart can contain at most %d items. Please remove some before checking out.', $wpide_max_cart_items ), 'error' );
}
} );
Notes
Change $max_items. The limit counts quantities, so 3 of one product counts as 3.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.