简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM