Replace whatever is in the cart when a new product is added, for stores that sell one plan, ticket or service at a time.
add_filter( 'woocommerce_add_to_cart_validation', function ( bool $passed ): bool {
if ( $passed && ! WC()->cart->is_empty() ) {
WC()->cart->empty_cart();
wc_add_notice( 'Your cart can hold one product at a time, so we replaced the previous one.', 'notice' );
}
return $passed;
} );
Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.
Membership plans, event tickets and service bookings often shouldn’t be combined in one order. This snippet keeps the cart to a single product: adding a new one replaces the old one.
WooCommerce runs woocommerce_add_to_cart_validation before adding a product. If the add is going ahead and the cart already has something in it, the snippet empties the cart first and shows a short notice explaining why. The new product is then added as normal.
Customers can still change the quantity of the one product.
Add one product to the cart, then another. The cart should contain only the second product, with a notice.