Capping number of items in woocommerce cart?

I’m wanting to limit the number of products in my cart to 6 maximum.
All products in my woocommerce setup are sold singularly (cannot buy multiples of the same product).

Example of Cart

Read More

eXAMPLE

Is there a way of limiting the cart to 6 products? So if the user goes to add a 7th, a warning will pop-up ‘Maximum of 6 products only. Please remove a product from your cart’?

Tried googling, but could only find this, limited to a singular product: Need Woocommerce to only allow 1 product in the cart

Related posts

1 comment

  1. It is the same procedure as the other question you linked to. On the validation filter, check the cart contents, and return a message if your requirements aren’t met. As mentioned, you would indeed use get_cart_contents_count() to count the number of line items in the cart.

    Edited: remove empty() check on cart

    function so_31516355_cap_cart_count( $valid, $product_id, $quantity ) {
    
        if( $valid && ( $quantity > 6 || intval( WC()->cart->get_cart_contents_count() ) > 6 || $quantity + intval( WC()->cart->get_cart_contents_count() ) > 6  ) ){
            $valid = false;
            wc_add_notice( 'Whoa hold up. You can only have 6 items in your cart', 'error' );
        }
    
        return $valid;
    
    }
    add_filter( 'woocommerce_add_to_cart_validation', 'so_31516355_cap_cart_count', 10, 3 );
    

    Added: validation on cart update

    function so_31516355_cap_cart_count_update( $valid, $cart_item_key, $values, $quantity ) {
        if( $valid && ( $quantity > 6 || intval( WC()->cart->get_cart_contents_count() ) > 6 || $quantity + intval( WC()->cart->get_cart_contents_count() ) > 6  ) ){
            $valid = false;
            wc_add_notice( __( 'Whoa hold up. You can only have 6 items in your cart', 'your-plugin' ), 'error' );
        }
    
        return $valid;
    }
    add_filter( 'woocommerce_update_cart_validation', 'so_31516355_cap_cart_count_update', 10, 4 );
    

Comments are closed.