skip to Main Content

I’ve been looking for a solution to disable certain products from the same category if one of the items is added to the cart.
For example: I have 1 category with products from A to E.
If I add product A to the cart I want to disable products B and E, so they can’t be added to the cart during the same shopping session.

Is there a way to achieve this?
Many thanks.

2

Answers


  1. Yes , you actually have two options ,one is to customize your own plugin and insert it to your website but this actually takes time .The other way is to download a wholesale and b2b plugin , these plugins usually contain features as the one you are looking for , so you will be able to activate the feature that you want .

    Login or Signup to reply.
  2. You can do that by validating the cart whenever an item is added to it.

    You can do that by editing your theme (or child theme) functions.php file or by using your custom plugin.

    You can use the following hook ‘woocommerce_add_to_cart_validation’

    add_filter( 'woocommerce_add_to_cart_validation', 'allowed_item_category_in_the_cart', 10, 2 );
    
    function allowed_item_category_in_the_cart( $passed, $product_id) {
      $product = wc_get_product($product_id);
    
      // Get product categories
      $product_category_ids = $product->get_category_ids();
    
      // Then you iterate through each cart item
      foreach (WC()->cart->get_cart() as $cart_item_key=>$cart_item ){
        $cart_product_id = $cart_item['product_id'];
        $cart_product = wc_get_product($cart_product_id);
        $cart_product_category_ids = $cart_product->get_category_ids();
        if (array_intersect($cart_product_category_ids, $product_category_ids))
          return false;
      }
    
      return true;
    }
    

    PS: I just wrote this code. I didn’t have time to test it yet.
    Let me know your feedback.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search