WooCommerce Remove Product From Cart Programmatically
Today we talk about WooCommerce or WordPress remove a product from the cart programmatically. In this tutorial, We focus on how to remove a product from the cart by product id. You need to first get a product cart id. Then you have to check either product exists in the cart or not. Then you can use the remove_cart_item to remove the product from that.
Let’s start with our example.
$productId = 1; // product id you want to remove from cat
$cartProductId = WC()->cart->generate_cart_id( $productId );
$cartItem = WC()->cart->find_product_in_cart( $cartProductId );
if ( $cartItem ) {
WC()->cart->remove_cart_item( $cartItem );
}
$cartProductId = WC()->cart->generate_cart_id( $productId );
$cartItem = WC()->cart->find_product_in_cart( $cartProductId );
if ( $cartItem ) {
WC()->cart->remove_cart_item( $cartItem );
}