Skip to main content
Login Join
Snippet · PHP

Automatically Empty the WooCommerce Cart Before Adding a Product

Shared by Amit Dholiya · August 18, 2026 · @woocommerce_add_to_cart_validation

6 views
Back to Snippets

For stores where customers should purchase only one product at a time, you can automatically empty the existing cart whenever a new product is added.

Steps

  1. Open your theme’s functions.php file.
  2. Add the code below.
  3. Save the file.
  4. Add a product to the cart and test it.

Done — the previous cart contents will be removed when a new product is added.

function empty_cart_before_adding_product(
    $passed,
    $product_id,
    $quantity
) {
    if ( WC()->cart ) {
        WC()->cart->empty_cart();
    }

    return $passed;
}

add_filter(
    'woocommerce_add_to_cart_validation',
    'empty_cart_before_adding_product',
    10,
    3
);
Know a different way to do this? Add your approach as a variation so folks can compare them side by side.
Submit a variation

0 comments