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
 * @donate $9     https://businessbloomer.com/bloomer-armada/
 */

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 this snippet?

You can place PHP snippets at the bottom of your child theme functions.php file (delete "?>" if you have it there). CSS, on the other hand, goes in your child theme style.css file. Make sure you know what you are doing when editing such files - if you need more guidance, please take a look at my free video tutorial "Where to Place WooCommerce Customization?"

Does this snippet (still) work?

Please let me know in the comments if everything worked as expected. I would be happy to revise the snippet if you report otherwise (please provide screenshots). I have tested this code with Storefront theme, the WooCommerce version listed above and a WordPress-friendly hosting on PHP 7.3.

If you think this code saved you time & money, feel free to join 14,000+ WooCommerce Weekly subscribers for blog post updates or 250+ Business Bloomer supporters for 365 days of WooCommerce benefits. Thank you in advance :)

Need Help with WooCommerce?

Check out these free video tutorials. You can learn how to customize WooCommerce without unnecessary plugins, how to properly configure the WooCommerce plugin settings and even how to master WooCommerce troubleshooting in case of a bug!

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.

28 thoughts on “WooCommerce: Remove Product From Cart Programmatically

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

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

  3. Not working (for variable products)

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

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

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

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

    1. What error do you get?

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

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

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

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

  11. 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? Support? Leave your Comment Now!
_____

If you are writing code, please wrap it between shortcodes: [php]code_here[/php]. Failure to complying with this (as well as going off topic, not writing in English, etc.) will result in comment deletion. 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 BloomerArmada to get blog comment reply priority, ask me 1-to-1 WooCommerce questions and enjoy many more perks. Thank you :)

Your email address will not be published.