php – WooCommerce: Only allow products from the same category in WordPress

Are you looking something to validate your Woocommerce Cart and allow users to add only same category products into cart. if they going to add other category products into cart than show them message and prevent to add other Category products into Cart.

Than im sure following code very useful for you. you just have to copy below complete code and add into your active theme functions.php file

function is_product_the_same_cat($valid, $product_id, $quantity) {
    global $woocommerce;
    if($woocommerce->cart->cart_contents_count == 0){
		 return true;
    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' );
        foreach ($terms as $term) {
            $cat_ids[] = $term->term_id;  
        foreach ($target_terms as $term) {
            $target_cat_ids[] = $term->term_id; 
    $same_cat = array_intersect($cat_ids, $target_cat_ids);
    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);

if you would like to change alert message than replace it in wc_add_notice()

  • Woocommerce add to Cart Validation in WordPress
  • Restrict other category product add to cart in Woocommerce
  • Allow only same category products add to cart
  • Same Category product only allow in Cart Woocommerce
  • Alert message on Add Other Category Product into woocommerce Cart
Scroll to Top