Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.