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 and checking what the current cart total is. If I go over the $50 threshold, the snippet loops through the cart items and stops if it finds the product. At this stage, it stores its “cart item key” and finally uses remove_cart_item() function to remove it.