Auto-Remove Products from WooCommerce Cart with Hooks

WooCommerce: Automatically Remove Products from Cart Using Code

Want to control which products stay in your WooCommerce cart? This guide shows how to remove items from the cart programmatically using WooCommerce action hooks.

Step 1: Trigger via woocommerce_cart_item_removed

Use this hook to catch when an item is removed and apply custom conditions to remove specific products automatically.

Paste the following into your functions.php or plugin file:

function custom_remove_product_from_cart($cart_item_key, $cart) {
    $product_id = $cart->cart_contents[$cart_item_key]['product_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);

Substitute YOUR_PRODUCT_ID_TO_REMOVE with the real product ID.

Step 2: Handle Logic via woocommerce_before_calculate_totals

This step ensures the product is removed before cart totals are finalized.

Use this:

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) {
        $product_id = $cart_item['product_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);

Step 3: Verify in a Staging Environment

After updating your site, test everything thoroughly before moving to production. Products with matching IDs will be removed instantly.

Backup Reminder: Save your files and test to avoid disruptions on your live site.

Common Use Cases
  • Preventing duplicate purchases
  • Dynamic cart management based on rules or roles

 

Leave a Comment

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

Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.