June 4, 2019
WooCommerce: Don’t Add Product To Cart If Already Exists
Put it in your theme’s functions.php.
Whenever your visiot will try to add a product twice mistakenly, it will keep only 1 of this product in his cart.
However, he will be still able to change the quantity of the single product he has in cart.
// disable double add to cart of a product add_filter('woocommerce_add_to_cart_validation', 'my_validation_handler', 10, 2); function my_validation_handler($is_valid, $product_id) { foreach(WC()->cart->get_cart() as $cart_item_key => $values) { if ($values['data']->id == $product_id) { return false; } } return $is_valid; }
Mr. Admin, you are a genius! I have been searching for a fix for this for many, many hours before stumbling upon your code! This works perfectly!
I have a coupon code that is set to one use per customer. If a user accidentally clicks the “Add To Cart” button more than once, enters the coupon code, and tries to check out, he/she gets an error message. Your code solves this problem, and it will really cut down on complaints and will hopefully increase sales.
For those products where purchases are not limited to one per purchase, I like that users have the ability to increase the quantity of single products in the cart.
While words cannot express my gratitude to you, I still wanted to take a moment to say, “Thank you! Thank you! Thank you!”
You welcome!!!
I’m glad to hear it helped you and I hope this will help others too
Thank you for the feedback and good luck!! 🙂
Not working for me.
Hello there
Does it return any error?
If not, please make sure you’ve cleared cache & OPCache.
Could we echo a message saying ‘the item is already in the cart’?
Right now the page only refreses
I didn’t test it but it should work:
add_filter('woocommerce_add_to_cart_validation', 'my_validation_handler', 10, 2);
function my_validation_handler($is_valid, $product_id) {
foreach(WC()->cart->get_cart() as $cart_item_key => $values) {
if ($values['data']->id == $product_id) {
wc_add_notice( __( 'This product is already in your cart.', 'woocommerce' ), 'error' );
return false;
}
}
}