Remove Product From Cart Programmatically Woocommerce

Remove Product From Cart Programmatically Woocommerce

Why Product From Cart Programmatically Code use?

Your customers may add items to their shopping basket and then return to it later. They might have been disrupted for a variety of reasons. In the meanwhile, one or more of the new goods may become unavailable.

Adding a product into a cart is very easy as you need the product ID of the items, but this is not the case for removing products. To remove products, you need to put in the “cart item key.”

How to remove products from the cart programmatically?

In this article, we will talk about how to remove a product from the cart with the help of a product ID. Other than adding products into a cart by itself, you also need to know how to remove products it. It gets a little tricky, though.

We can remove products from the WooCommerce cart using the remove_cart_item() function with $product_id.

<?php
add_action( 'template_redirect', 'cxc_remove_product_from_cart_programmatically' );

function cxc_remove_product_from_cart_programmatically() {
	if ( is_admin() ){
		return;
	}
	$product_id = 40; // 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 );
	}
}
?>

Code goes into function.php file of your active child theme (or active theme).

Conclusion

For the theme, you can use this PHP code snippet at the end of your child function. As you can see in the code, it has a function called “woocommerce_remove_product_from_cart(),” This function uses the product_id (this example has the id 123 used) and then generates the “cart item key” by locating the item with the product id in the cart. The item is removed if a match is found in the cart.
 
The CSS for this code snippet goes into your style.css file for the webpage for your e-commerce website.

Note: If you add the code to your functions.php file, you must remove the first ?PHP tag because functions.php already has one.

Was this article helpful?
YesNo

Leave a comment

Your email address will not be published. Required fields are marked *