Search code examples
phpwordpresswoocommercecartcategories

Woocommerce sold individually feature based on product categories


I have a woocommerce site I use the booster plugin to enable sold individually for each product but now I want to sold individually for each category and if someone add a product to cart on a category then can not add another product of that category to cart


Solution

  • In the code below there is 2 functions:

    • The 1st one is a conditional function checking categories in cart items
    • The 2nd one will avoid add to cart when a product category already exist in cart items and will display a custom message.

    The code:

    // Conditional function: Checking product categories in cart items
    function check_cats_in_cart( $product_id ) {
        $taxonomy = 'product_cat';
        $has_term = true;
    
        foreach( WC()->cart->get_cart() as $item ){
            foreach( wp_get_post_terms( $item['product_id'], $taxonomy ) as $term ){
                // Allowing add to cart the same product
                if( has_term( $term->slug, $taxonomy, $product_id ) ){
                    $has_term = false;
                    break; // stops the 2nd loop
                }
            }
            // Allowing the same product to be added (not activated. you can uncomment lines below)
            # if ( $item['product_id'] == $product_id  )
            #   $has_term = true;
    
            if( $has_term )
                break; // stops the 1st loop
        }
        return $has_term;
    }
    
    // Avoid add to cart when a product category already exist in cart items, displaying a custom error message
    add_filter( 'woocommerce_add_to_cart_validation', 'sold_individually_by_cats_valid', 10, 3 );
    function sold_individually_by_cats_valid( $passed, $product_id, $quantity) {
    
        $passed = check_cats_in_cart( $product_id );
    
        if( ! $passed ){
            // Displaying a custom message
            $message = __("This product category is already in cart. Try another product", "woocommerce");
            wc_add_notice( $message, 'error' );
        }
        return $passed;
    }
    

    Code goes in function.php file of the active child theme (or active theme).

    Tested and works.

    If you want to allow adding to cart again the same product (that increases only the quantity of an existing product), you will uncomment this code in the function:

           if ( $item['product_id'] == $product_id  )
    
                $has_term = true;