# 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.

- Type: PHP
- Runs: Run everywhere
- Category: [WooCommerce](https://wpide.com/library/category/woocommerce/)
- Requires: WooCommerce
- Tags: woocommerce, cart, limits
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/woo-max-cart-items/

## Code

```php
$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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Limit the Number of Items in the Cart" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
