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.
/** * @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 ); }