WooCommerce: Remove Product From Cart Programmatically
We already saw how to add a product to cart automatically, for example if you visit a specific page or if there are no products in the cart – but today we want to find out how to do the opposite: if a certain condition is met, we want to remove a product ID from the cart.
This becomes a little complex – while adding an item to cart requires just its product ID, removing it from the cart forces you to know the “cart item key”. Japanese, I know, but just copy the snippet and you’re done!
PHP Snippet: Remove Item from Cart Automatically
In the example below, I’m targeting product ID = 282 – the snippet looks for its “cart item key” and uses remove_cart_item() function to remove it.
This code still works, unless you report otherwise. To exclude conflicts, temporarily switch to the Storefront theme, disable all plugins except WooCommerce, and test the snippet again: WooCommerce troubleshooting 101
Related content
WooCommerce: Custom Add to Cart URLs – The Ultimate Guide In WooCommerce you can add a product to the cart via a custom link. You just need to use the “add-to-cart” URL parameter followed by the product ID. This tutorial will show you how to create custom URLs to add simple, variable and grouped products to the cart – as well as defining the add […]
WooCommerce: Hide Price & Add to Cart for Logged Out Users You may want to force users to login in order to see prices and add products to cart. That means you must hide add to cart buttons and prices on the Shop and Single Product pages when a user is logged out. All you need is pasting the following code in your functions.php (please note: […]
WooCommerce: How to Fix the “Cart is Empty” Issue For some reason, sometimes you add products to cart but the cart page stays empty (even if you can clearly see the cart widget has products in it for example). But don’t worry – it may just be a simple cache issue (and if you don’t know what cache is that’s no problem either) or […]
WooCommerce: Remaining $$$ to Get Free Shipping Notification @ Cart This is a very cool snippet that many of you should use to increase your average order value. Ecommerce customers who are near the “free shipping” threshold will try to add more products to the cart in order to qualify for free shipping. It’s pure psychology. So, here’s how we show a simple message on […]
WooCommerce: Cart and Checkout on the Same Page This is your ultimate guide – complete with shortcodes, snippets and workarounds – to completely skip the Cart page and have both cart table and checkout form on the same (Checkout) page. But first… why’d you want to do this? Well, if you sell high ticket products (i.e. on average, you sell no more than […]
Rodolfo Melogli
Business Bloomer Founder
Author, WooCommerce expert and WordCamp speaker, Rodolfo has worked as an independent WooCommerce freelancer since 2011. His goal is to help entrepreneurs and developers overcome their WooCommerce nightmares. Rodolfo loves travelling, chasing tennis & soccer balls and, of course, wood fired oven pizza. Follow @rmelogli
35 thoughts on “WooCommerce: Remove Product From Cart Programmatically”
Hey guys, a lot of you’ll are saing that the code doesn’t work, but it does still! However… here goes the entire pice of code you need, in the post is not clear that to trigger the event, you need to join the provided code in this article with the previous one mentioned at the begining. So… here goes the complete piece of code. Still working today. Enjoy it, peace out, and hugs from Brasil!
add_action( 'wp', 'yib_remove_product_from_cart_on_page_id_load' );
function yib_remove_product_from_cart_on_page_id_load() {
// page ID you wannna trigger to do the action.
//if ( is_page( yib_custom_url_id() ) ) { <------------Page (Change "yib_custom_url_id()" by your page id or 'title'.
if ( is_single( yib_custom_url_id() ) ) { // <------------Post (Change "yib_custom_url_id()" by your post id or 'title'.
//WC()->cart->empty_cart(); <- This just empty all the products in the cart.
//WC()->cart->add_to_cart( $product_id ); <---- If you want to add the product to cart, instead, thats is the line.
//All the lines above are the ones necessary to remove the product from the cart
$product_cart_id = WC()->cart->generate_cart_id( yib_product_id() );
$cart_item_key = WC()->cart->find_product_in_cart( $product_cart_id );
if ( $cart_item_key ) WC()->cart->remove_cart_item( $cart_item_key );
}
}
Okay, So I wonder if we could remove the existing product when adding the new one to the cart.
In more in-depth
I have 3 products and when somebody adds my products to their cart but won’t make the purchase and leave. it remains in the cart but if they return and choose the other product then both of the products were added and I don’t use the cart page so the checkout page total bill looks higher and I don’t want that coz I don’t want to scare them you know
can we solve that via code
Hey Ibe, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!
by any chance, do you have a snippet to automatically remove all the products from the user’s cart if the user changes their shipping country or shipping state? Thanks
I’m working on it too. if I achieve it using a snippet before anyone else shares it here, I’ll share it myself. but if anyone else already has that snippet, that could save a big time now ๐
Hi,
Thank you for your amazing work !
I am looking for a snippet who would do like that :
– I have a product category which is called “sample”. That products will be free
– I want to remove automatically the products from that “sample” category if no other products (from other categories) are in the cart. In order customers can’t order free samples alone
Regards
Hi Trev, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!
Why do you call the same function e.g. WC()?
Do you expect different result?
Within the same function?
Are you crazy by any chance? That’s certainly is the definition.
Please give me a good reason?
Because IMO here’s 3 reason why it’s not a good idea.
It’s ugly as F… it’s slow. And it’s an AXX to debug.
Here are 1 more reasons:
When I say slow, I mean; 3 is not slow, but when you have over 10000 of them.
It’s starting to wear you down.
As for the reason as of why you should not that:
Because, most people getting your lessons won’t think.
They will just copy.
So, in other words; you giving them bad habit.
Kind regards,
Denis
Appreciate your feedback and your passion – but let me tell you one thing. I’m publishing your comment just to show the other 70,000 monthly readers how NOT TO comment on my blog.
I’m not crazy, it’s not ugly, no debug is needed, and unfortunately it seems you didn’t understand how the function works. I recommend you read a bit of Woo documentation (if you can manage to find it), or study the WooCommerce code. Only then, come back here and post a reply.
Hi Koyaldas, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!
Hi, thank you very much for your wonderful content. I had a question. Is it possible for the cart page to be automatically refreshed after each item is deleted?
Hi Reza, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!
Is this still working as tried not and seen other links talking about the cart key having a new hook. I Tried the below and which is the cart page to test if it removed visiting that page and didn’t seem remove product tried hard refreshing and making sure cache cleared on site to this is added to my functions.php file
The earlier code 3rd line wasn’t used and removed. I was trying to have it trigger and remove product if they went to a specific page.
I also tried to just generate the cart item key and echo it but that was blank so not sure what was wrong, the function worked as could echo word test if I changed it to equal that instead so think it is probably some sort of conflict then if working on yours still.
Anyways thanks for ideas and everything you do is great, I have come up with a different solution just anchoring to the item for removing in cart not as good but working for now.
I’m trying to use this code and it doesn’t seem to be working. Does WC()->cart->find_product_in_cart return true or false? If so should this line be changed to
if ( $cart_item_key ) WC()->cart->remove_cart_item( $product_cart_id );
thanks for this, but I was wondering if you could explain it a little more for me. Is this function called when you click the remove (red x) button in the cart?
Could you let me know how to amend the code such that if a user adds one product, then it will automatically remove all other products that have been previously added to the cart?
How would you write it so that if someone adds a product to the cart, IE: [Product ID 1] which also requires another product to be added to the cart [Product ID 2], but if they remove the original product, programatically remove [Product ID 2].
Adding [Product ID 1] to cart will automaticly add [Product ID 2] as it’s required as well,
However –
If they remove [Product ID 1], programatically it will remove [Product ID 2] also.
Questions? Feedback? Customization? Leave your comment now! _____
If you are writing code, please wrap it like so: [php]code_here[/php]. Failure to complying with this, as well as going off topic or not using the English language will result in comment disapproval. You should expect a reply in about 2 weeks - this is a popular blog but I need to get paid work done first. Please consider joining the Business Bloomer Club to get quick WooCommerce support. Thank you!
Hey guys, a lot of you’ll are saing that the code doesn’t work, but it does still! However… here goes the entire pice of code you need, in the post is not clear that to trigger the event, you need to join the provided code in this article with the previous one mentioned at the begining. So… here goes the complete piece of code. Still working today. Enjoy it, peace out, and hugs from Brasil!
Ohh, also change the “yib_product_id()” in line 9 by your product id to remove, like:
Thank you!
Okay, So I wonder if we could remove the existing product when adding the new one to the cart.
In more in-depth
I have 3 products and when somebody adds my products to their cart but won’t make the purchase and leave. it remains in the cart but if they return and choose the other product then both of the products were added and I don’t use the cart page so the checkout page total bill looks higher and I don’t want that coz I don’t want to scare them you know
can we solve that via code
Hey Ibe, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!
No, This doesn’t work for me. It didn’t gave any error but didn’t remove the product.
if you want, I can share the code as well which I have tried to apply.
Of course, please do
by any chance, do you have a snippet to automatically remove all the products from the user’s cart if the user changes their shipping country or shipping state? Thanks
I’m working on it too. if I achieve it using a snippet before anyone else shares it here, I’ll share it myself. but if anyone else already has that snippet, that could save a big time now ๐
Thank you – no I don’t have anything like that available at the moment
Hi,
Thank you for your amazing work !
I am looking for a snippet who would do like that :
– I have a product category which is called “sample”. That products will be free
– I want to remove automatically the products from that “sample” category if no other products (from other categories) are in the cart. In order customers can’t order free samples alone
Regards
Hi Trev, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!
Not working (for variable products)
Thanks for that Marco. Did you use the variation ID instead of the product ID?
Why do you call the same function e.g. WC()?
Do you expect different result?
Within the same function?
Are you crazy by any chance? That’s certainly is the definition.
Please give me a good reason?
Because IMO here’s 3 reason why it’s not a good idea.
It’s ugly as F… it’s slow. And it’s an AXX to debug.
Here are 1 more reasons:
When I say slow, I mean; 3 is not slow, but when you have over 10000 of them.
It’s starting to wear you down.
As for the reason as of why you should not that:
Because, most people getting your lessons won’t think.
They will just copy.
So, in other words; you giving them bad habit.
Kind regards,
Denis
Hi Denis!
Appreciate your feedback and your passion – but let me tell you one thing. I’m publishing your comment just to show the other 70,000 monthly readers how NOT TO comment on my blog.
I’m not crazy, it’s not ugly, no debug is needed, and unfortunately it seems you didn’t understand how the function works. I recommend you read a bit of Woo documentation (if you can manage to find it), or study the WooCommerce code. Only then, come back here and post a reply.
Cheers
On my site user can add same product with different variation, so I want to delete product having specific variation id, how to achieve this?
Hi Koyaldas, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!
this does not work on my site. please help me. I need this function.
What error do you get?
Hi, thank you very much for your wonderful content. I had a question. Is it possible for the cart page to be automatically refreshed after each item is deleted?
Hi Reza, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!
Is this still working as tried not and seen other links talking about the cart key having a new hook. I Tried the below and which is the cart page to test if it removed visiting that page and didn’t seem remove product tried hard refreshing and making sure cache cleared on site to this is added to my functions.php file
Hi Jay, your code is different than mine so not sure. Mine still works ๐
The earlier code 3rd line wasn’t used and removed. I was trying to have it trigger and remove product if they went to a specific page.
I also tried to just generate the cart item key and echo it but that was blank so not sure what was wrong, the function worked as could echo word test if I changed it to equal that instead so think it is probably some sort of conflict then if working on yours still.
Anyways thanks for ideas and everything you do is great, I have come up with a different solution just anchoring to the item for removing in cart not as good but working for now.
Ok cool
I’m trying to use this code and it doesn’t seem to be working. Does WC()->cart->find_product_in_cart return true or false? If so should this line be changed to
?
No, it returns the cart item key
thanks for this, but I was wondering if you could explain it a little more for me. Is this function called when you click the remove (red x) button in the cart?
Nope, it runs on every page load
Could you let me know how to amend the code such that if a user adds one product, then it will automatically remove all other products that have been previously added to the cart?
Sure: https://businessbloomer.com/woocommerce-allow-1-product-cart/
How would you write it so that if someone adds a product to the cart, IE: [Product ID 1] which also requires another product to be added to the cart [Product ID 2], but if they remove the original product, programatically remove [Product ID 2].
Adding [Product ID 1] to cart will automaticly add [Product ID 2] as it’s required as well,
However –
If they remove [Product ID 1], programatically it will remove [Product ID 2] also.
Not sure. This could be a start: https://www.businessbloomer.com/woocommerce-add-item-to-cart-programmatically/