Programmatically Remove Items from WooCommerce Cart

How to Programmatically Remove Products from WooCommerce Cart

In this tutorial, you’ll learn how to remove a product from the WooCommerce cart programmatically using WordPress hooks. This method helps remove products based on specific conditions.

Step 1: Use woocommerce_cart_item_removed Hook

The woocommerce_cart_item_removed action triggers when an item is removed from the cart. Use it to set your custom condition for removing a product.

Add this snippet to your theme’s functions.php file or a custom plugin:

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);

Replace YOUR_PRODUCT_ID_TO_REMOVE with the product ID you want to target.

Step 2: Use woocommerce_before_calculate_totals Hook

This hook lets you remove a product just before WooCommerce calculates the cart totals.

Here’s the code:

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: Test Your Changes

After saving the code, test in a staging environment. Products with the specified ID should be removed automatically when added to the cart.

Important: Always back up your website and test changes thoroughly to avoid impacting the live user experience.

Use Cases for Automatic Product Removal
  • Restricting products for specific user roles
  • Conditionally removing items when certain coupons apply

 

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.