• Hello guys,

    I am looking to set-up a rule for my woocommerce store.
    I have two categories in my store (Category A and Category B) I want to set a rule that the customers can order items only from Category A and not be allowed to order from Category B, and the other way around.

    I’ve searched the web and there’s no plugin or module that covers this.
    All I was able to find is this piece of code which I think will do the trick (but I don’t code in php).

    function is_product_the_same_cat($valid, $product_id, $quantity) {
        global $woocommerce;
        // start of the loop that fetches the cart items
        foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
            $_product = $values['data'];
            $terms = get_the_terms( $_product->id, 'product_cat' );
            $target_terms = get_the_terms( $product_id, 'product_cat' ); //get the current items
            foreach ($terms as $term) {
                $cat_ids[] = $term->term_id;  //get all the item categories in the cart
            }
            foreach ($target_terms as $term) {
                $target_cat_ids[] = $term->term_id; //get all the categories of the product
            }           
        }
        $same_cat = array_intersect($cat_ids, $target_cat_ids); //check if they have the same category
        if(count($same_cat) > 0) return $valid;
        else {
            wc_add_notice( 'This product is in another category!', 'error' );
            return false;
        }
    }
    add_filter( 'woocommerce_add_to_cart_validation', 'is_product_the_same_cat',10,3);

    From what I understand I need to specify my category ID’s in the bottom line of code.
    So I do, but still does not work properly and throws out the error code for – This product is in another category!

    Let me know if you can ready this and help me out.

    Regards

Viewing 1 replies (of 1 total)
  • Moderator bcworkz

    (@bcworkz)

    I see no reason to specify categories anywhere, the script picks up categories from the cart and item for comparison. The one problem is it won’t let you add any item if the cart is empty. I think the get cart function should be called initially and if it is empty, bypass the whole thing and return $valid.

    The script seemed to fail intermittently, but I’m not sure why. It may be related to where the item was added from. Your site may not have such areas, so maybe it’s fine. Be sure to test adding items from all possible locations.

Viewing 1 replies (of 1 total)
  • The topic ‘WooCommerce – Limit Customer to Purchase from 1 Category’ is closed to new replies.