To remove a product from the cart programmatically in WooCommerce, you can use the woocommerce_cart_item_removed
and woocommerce_before_calculate_totals
hooks. Here’s how you can do it:
Step 1: Hook into woocommerce_cart_item_removed
Add the following code to your theme’s functions.php file or a custom plugin:
function custom_remove_product_from_cart($cart_item_key, $cart) { // Get the product ID to be removed from the cart $product_id = $cart->cart_contents[$cart_item_key]['product_id']; // Check if you want to remove a specific product based on its ID if ($product_id === YOUR_PRODUCT_ID_TO_REMOVE) { unset($cart->cart_contents[$cart_item_key]); } } add_action('woocommerce_cart_item_removed', 'custom_remove_product_from_cart', 10, 2);
Replace YOUR_PRODUCT_ID_TO_REMOVE
with the actual product ID you want to remove from the cart.
Step 2: Hook into woocommerce_before_calculate_totals
Add the following code to your theme’s functions.php file or a custom plugin:
function custom_remove_product_from_cart_on_calculate_totals($cart) { if (is_admin() && !defined('DOING_AJAX')) { return; } foreach ($cart->get_cart() as $cart_item_key => $cart_item) { // Get the product ID to be removed from the cart $product_id = $cart_item['product_id']; // Check if you want to remove a specific product based on its ID if ($product_id === YOUR_PRODUCT_ID_TO_REMOVE) { $cart->remove_cart_item($cart_item_key); } } } add_action('woocommerce_before_calculate_totals', 'custom_remove_product_from_cart_on_calculate_totals', 10, 1);
Again, replace YOUR_PRODUCT_ID_TO_REMOVE
with the actual product ID you want to remove from the cart.
Step 3: Save Changes and Test Save the changes to your functions.php file or custom plugin. Now, when you add the specific product with the provided product ID to the cart, it will be removed automatically.
Remember to test the functionality thoroughly to ensure it’s working as expected. Always make sure you have a backup of your site before making any significant changes to the code.