Musa Baltacı
Musa Baltacı

Reputation: 91

Limit the number of different products allowed in WooCommerce cart

Using Limit the number of cart items in Woocommerce answer, I can limit total product quantity in cart page on my store. But I need to limit the number of different items in cart, but keep quantities unlimited and limit to total product price amount.

For example 10 items in my cart but total product quantity is 50, and total products price amount is 5000. if I set the different product quantity in cart 10 and total price amount 5000, my customers cant add another one product to their cart.

How can I do this?

Upvotes: 0

Views: 926

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 254398

You can use the following to Limit the number of different products allowed to be added to cart:

// Checking and validating when products are added to cart
add_filter( 'woocommerce_add_to_cart_validation', 'only_n_products_allowed_in_cart', 10, 3 );
function only_n_products_allowed_in_cart( $passed, $product_id, $quantity ) {
    $items_limit = 10;
    $total_count = count( WC()->cart->get_cart() ) + 1;

    if( $total_count > $items_limit ){
        // Set to false
        $passed = false;
        // Display a message
         wc_add_notice( sprintf( __( "You can’t have more than %s different products in cart", "woocommerce" ), $items_limit ), "error" );
    }
    return $passed;
}

Code goes in functions.php file of the active child theme (or active theme).

Upvotes: 2

Related Questions