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
- Open your theme’s
functions.phpfile. - Add the code below.
- Save the file.
- 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
);