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!

How to automatically remove a product from the Cart

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.

/**
 * @snippet       Remove Cart Item Programmatically - WooCommerce
 * @how-to        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @compatible    WooCommerce 3.8
 * @community     https://businessbloomer.com/club/
 */

add_action( 'template_redirect', 'bbloomer_remove_product_from_cart_programmatically' );

function bbloomer_remove_product_from_cart_programmatically() {
   if ( is_admin() ) return;
   $product_id = 282;
   $product_cart_id = WC()->cart->generate_cart_id( $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 );
}

Where to add custom code?

You should place custom PHP in functions.php and custom CSS in style.css of your child theme: where to place WooCommerce customization?

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: “You Only Need $$$ to Get Free Shipping!” @ 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. Here’s how we show a simple message on the […]
  • 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

  1. 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 );
    	}    
    }
    
    1. Ohh, also change the “yib_product_id()” in line 9 by your product id to remove, like:

       $product_cart_id = WC()->cart->generate_cart_id( 1234 ); 
  2. 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

    1. 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!

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

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

    1. 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 ๐Ÿ˜‰

      1. Thank you – no I don’t have anything like that available at the moment

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

    1. 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!

  6. Not working (for variable products)

    1. Thanks for that Marco. Did you use the variation ID instead of the product ID?

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

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

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

  8. 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?

    1. 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!

  9. this does not work on my site. please help me. I need this function.

    1. What error do you get?

  10. 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?

    1. 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!

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

    add_action( 'wp', 'bbloomer_remove_product_from_cart_programmatically' );
    function bbloomer_remove_product_from_cart_programmatically() {
    $url = $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
       $product_id = 51675;
            if (is_page( 394 )){
       $product_cart_id = WC()->cart->generate_cart_id( $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 );
    }
    }
    
    1. Hi Jay, your code is different than mine so not sure. Mine still works ๐Ÿ™‚

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

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

    ?

    1. No, it returns the cart item key

  13. 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?

    1. Nope, it runs on every page load

  14. 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?

      1. 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!

Your email address will not be published. Required fields are marked *