I would like Woocommerce to only allow 1 product in the cart. If a product is already in the cart and another one is added then it should remove the previous one.
I foun
This one is the more compact and actual code as global $woocommerce
is not needed anymore:
add_filter( 'woocommerce_add_to_cart_validation', 'auto_empty_cart', 20, 3 );
function auto_empty_cart( $passed, $product_id, $quantity ) {
if( WC()->cart->is_empty() ) return $passed; // Exit
WC()->cart->empty_cart();
return $passed;
}
Code goes in function.php file of your active child theme (or active theme).
Tested and works in all Woocommerce versions since 2.6.x