WooCommerce PHP Intermediate Requires WooCommerce

Allow Only One Product in the Cart

Replace whatever is in the cart when a new product is added, for stores that sell one plan, ticket or service at a time.

Tested on WordPress 7.1 PHP 8.3 Updated
functions.php 7 lines
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;
} );

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

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.

How it works

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.

Things to watch

  • To block the add instead of replacing, return false with an error notice rather than emptying the cart.
  • Products added through the Store API, such as by product blocks, also run this validation.

How to test it

Add one product to the cart, then another. The cart should contain only the second product, with a notice.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only