Remove conditionally Woocommerce cart items based on a specific product

The following will remove conditionally cart items based on a specific product: When the specific product is added to cart, all other items are removed. When any other product is added to cart, it removes the specific product (if it's in cart)


1 min read
Remove conditionally Woocommerce cart items based on a specific product

Hi ,

If you have  a bookable or subscription product that can be purchased only alone without any other products this snippet may come in your use.

The following will remove conditionally cart items based on a specific product:

  • When the specific product is added to cart, all other items are removed.
  • When any other product is added to cart, it removes the specific product (if it's in cart)

Here is the code:

You need to just change the number here to your woocommerce product id.

$specific_product_id = 37; 

There are many ways of getting your woocommerce product id but the easiest way is to get it from Products page like shown below.

Using this snippet for multiple products :

For multiple products , we can use this snippet by changing the function name in the first line , suppose if you have two products.

In both lines it should be the same name but it should be different in each “repeated code”. So each “copy of the code” would start with e.g.

first instance :

add_action( 'woocommerce_before_calculate_totals', 'remove_cart_items_conditionally_a', 10, 1 );
function remove_cart_items_conditionally_a( $cart ) {

... and the rest of original code goes here

second instance :

add_action( 'woocommerce_before_calculate_totals', 'remove_cart_items_conditionally_b', 10, 1 );
function remove_cart_items_conditionally_b( $cart ) {

... and the rest of original code goes here

Thats it , now you can add this to as many products , I am working on a snippet for a category too , will add it soon here.

How to add this snippet?

You can add this snippet to your child themes functions.php , We don't recommend adding code to your main theme if its not developed by you. Otherwise you can use a simple plugin https://wordpress.org/plugins/code-snippets/

Express your views in the comment section below.

GO TOP

🎉 You've successfully subscribed to NCY Design !
OK