How to Use woocommerce_remove_cart_item Hook to Remove product from cart

How to Use woocommerce_remove_cart_item Hook to Remove product from cart

Looking for an easy and quick way to remove products available in the cart by firing woocommerce_remove_cart_item . Shorten your time and efforts while taking the assistance of WooCommerce for moving to the next. Here, you got a step-by-step guide for the WooCommerce_remove_cart_item hook, followed by a detailed example of how it works. Removing a cart item needs to know cart_item_key and product ID.

The following steps are mentioned below that is necessary to remove a cart item while utilizing product ID –

  • First of all, we need to generate Cart ID from Product ID,
  • and then, Find the product available in the cart using Product ID,
  • finally, remove the product which you want to remove from the cart.

Apply this simple code mentioned below and remove the item available in the cart by firing woocommerce_remove_cart_item


add_action( 'woocommerce_remove_cart_item', 'gomaya_remove_cart_item', 10, 2 );
function gomaya_remove_cart_item( $cart_item_key, $cart ) {
// Get the product ID of the item being removed
$product_id = $cart->cart_contents[ $cart_item_key ]['product_id'];
// Check if the product ID is equal to the ID of the product you want to remove
if ( $product_id == 5 ) {
// Remove the item from the cart
$cart->remove_cart_item( $cart_item_key );
}
}

In the above example woocommerce_remove_cart_item will Remove Product From Cart having product id 5 you can change it to your product id.

 

If you want to remove all product from the cart then you should try this code

add_action( 'woocommerce_remove_cart_item', 'gomaya_remove_all_cart_items_function', 10, 2 );
function gomaya_remove_all_cart_items_function( $cart_item_key, $cart ) {
// Loop through all items in the cart
foreach ( $cart->cart_contents as $key => $value ) {
// Remove the item from the cart
$cart->remove_cart_item( $key );
}
}

Leave a Reply

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

Post comment