WooCommerce – Limit Customer to Purchase from 1 Category
-
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
- The topic ‘WooCommerce – Limit Customer to Purchase from 1 Category’ is closed to new replies.