WooCommerce How to Remove Product from Cart Programmatically

An e-commerce site involves adding products into cart and removing them from the cart. This functionality enables easy user experience on your website. Further, in this tutorial, we will identify how to remove product from woocommerce cart programmatically.

Where adding a product to cart requires just a product ID, removing it from the cart requires ‘cart item key’. The removal process is a bit complex but we have made it easier & clearer below. You can copy the snippet below to enable the functionality.

Image on how to remove product from cart

PHP Snippet: Remove Product from Cart Programmatically

In the below example, we will use remove_cart_item() function to remove products from cart automatically. Further, the snippet uses ‘cart item key’. 

add_action( 'template_redirect', 'phpsof_remove_product_from_cart_programmatically' );
 
function phpsof_remove_product_from_cart_programmatically() {
   if ( is_admin() ) return;
   $product_id = 369; // Your product id
   $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 the snippet?

So, to remove product from cart, the above snippet can be placed in either of the following two places. One way is to place it at the bottom of your child theme functions.php file (delete “?>”, if you have any). Another way suggests to put CSS in your child theme style.css file. 

Also Read, A Guide to Create WooCommerce Custom Login and Registration Pages

A Complete Tutorial to Compress Image before upload using PHP