Woocommerce – Empty cart when products in a specific category are added to cart?

How can I get the cart to empty when a product from a specific category is added to the cart, in Woocommerce?

I found the following code which empties the cart when ANY product is added to the cart, but I need this to only apply when the product is from a specific category:

  add_filter( 'woocommerce_add_cart_item_data', 'wdm_empty_cart', 10,  3);

  function wdm_empty_cart( $cart_item_data, $product_id, $variation_id ) {

   global $woocommerce;
   $woocommerce->cart->empty_cart();

   // Do nothing with the data and return
   return $cart_item_data;
  }

Related posts

1 comment

  1. Found a solution. Not sure why this works compared to other solutions I’ve tried, but it works!

    add_filter( 'woocommerce_add_cart_item_data', 'wdm_empty_cart', 10,  3);
    
    function wdm_empty_cart( $cart_item_data, $product_id, $variation_id ) {
    
     global $woocommerce;
    
     //Check if product ID is in a certain category
     if( has_term( 'category-slug', 'product_cat', $product_id ) ){
    
      $woocommerce->cart->empty_cart();
     }
    
     //Do nothing with the data and return
     return $cart_item_data;
    
    }
    

Comments are closed.