Home » WooCommerce: Remove Product From Cart Programmatically

WooCommerce: Remove Product From Cart Programmatically

by Tutor Aspire

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 tutoraspire.com FREE
 * @author        Tutor Aspire
 * @compatible    WooCommerce 3.8
 * @donate $9     https://tutoraspire.com
 */

add_action( 'template_redirect', 'tutoraspire_remove_product_from_cart_programmatically' );

function tutoraspire_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 );
}

You may also like