I’m using WooCommerce and trying to limit the cart to 10 products only. With the below code in my functions.php
, it works perfectly.
function limit_cart_allowed_add_to_cart( $passed, $product_id, $quantity ) {
$cart_items_count = WC()->cart->get_cart_contents_count();
$total_count = $cart_items_count + $quantity;
if ( $cart_items_count >= 10 || $total_count > 10 ) {
$passed = false;
}
return $passed;
}
// Checking and validating when products are added to cart
add_filter( 'woocommerce_add_to_cart_validation', 'limit_cart_allowed_add_to_cart', 10, 3 );
function limit_cart_allowed_cart_update( $passed, $cart_item_key, $values, $updated_quantity ) {
$cart_items_count = WC()->cart->get_cart_contents_count();
$original_quantity = $values[ 'quantity' ];
$total_count = $cart_items_count - $original_quantity + $updated_quantity;
if ( $cart_items_count > 10 || $total_count > 10 ) {
$passed = false;
}
return $passed;
}
// Checking and validating when updating cart item quantities when products are added to cart
add_filter( 'woocommerce_update_cart_validation', 'limit_cart_allowed_cart_update', 10, 4 );
However, there is one problem and I just noticed it yesterday and until now I couldn’t find a solution.
The AJAX for adding product to cart is no longer working. There’s an option from the settings of WooCommerce to enable AJAX Add to Cart function, it’s enabled but it’s not working anymore because of the code above.
When I tried adding product to cart and when the products in the cart are already 10, it redirects me into the single product page. It shouldn’t be like that, I want to keep the ajax functionality but just limit the cart into 10 products.
2
Answers
I'd like to add this as comment, but for the sake of code format I'll put this as answer instead.
In woocommerce-ajax.php, you'll see how it works.
If
$passed_validation
is true, then it will work as normal adding product into the cart via ajax, now since you're setting it to false with your hookwoocommerce_add_to_cart_validation
andwoocommerce_update_cart_validation
then it is normal to redirect into single product page to show the error message.I have 2 different ways in my mind to solve this.
Leave it, accept the fact that it will redirect into single product page once there was an error adding product into the cart. What you can do is by adding notice message, for example.
Override the
wp_ajax_woocommerce_add_to_cart
hook to not to return the URL.Min and Max Quantity for WooCommerce plugin allow you to set up limits for the cost of products in orders and in groups and limits for the quantity of products, product variations, products in orders, and products in the group. You can add products and product variations to the group. The infinite amount of groups.
Reference: https://mahbub.me/how-to-limit-min-and-max-quantity-for-woocommerce/