← Back to All Snippets

Automatically Empty Cart Before Adding New Product in WooCommerce

⚡ Target: functions.php 🔒 Tested: WooCommerce 8.0+ / WP 6.6+ 💻 Lang: PHP
PHP (functions.php)
add_filter( 'woocommerce_add_to_cart_validation', function( $passed, $product_id, $quantity ) {
    if ( ! WC()->cart->is_empty() ) {
        WC()->cart->empty_cart();
    }
    return $passed;
}, 10, 3 );

When selling digital products, booking services, or individual course memberships, you often want only one item in the WooCommerce cart at any time. This hook clears the existing cart before adding a new product.

← Back to All Snippets Explore Dev Tools →