Limit woocommerce basket size

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' );
    }
}
}

Related posts

1 comment

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

    function so_33134668_product_validation( $valid, $product_id, $quantity ){
        // 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;
    
        $future_quantity_in_cart = $cart_num_products + $quantity;
    
        // More than 5 products in the cart is not allowed
        if( $future_quantity_in_cart > $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' );
            $valid = false; // don't add the new product to the cart
        }
        return $valid;
    }
    add_filter( 'woocommerce_add_to_cart_validation', 'so_33134668_product_validation', 10, 3 );
    

Comments are closed.