Check if product’s category’s or its child’s page is being displayed in WooCommerce

In a woocommerce store there are multiple product categories, f.x. toys, clothes, shoes, adults which have a few child categories each. The products from adults category have to be blurred if it is not the adults or its child category that is being displayed.

What I do in the loop for now is this:

Read More
   $for_adults = has_term( 106, 'product_cat' );

   if( $for_adults  && !is_product_category( 'adults' )){
         echo '<img src="'.$image_src.'" alt="'.get_the_title().'" class="product-image blur" title="'.get_the_title().'">';
   }else{
         echo '<img src="'.$image_src.'" alt="'.get_the_title().'" class="product-image" title="'.get_the_title().'">';
   }

The problem is that is_product_category( 'adults' ), only returns true for when the exact category is being displayed and what needs to be done is that it would return true for when child categories pages are being displayed without hard-coding the category slugs.

Any help or gudance is much appreciated.

Related posts

2 comments

  1. Here you go:

    // Get the term
    $for_adults = get_term_by( 'slug', 'adults', 'product_cat' );
    
    // Get the term ancestors
    $product_parent_categories_all_hierachy = get_ancestors( $for_adults->term_id, 'product_cat' );
    
    $parent_is_adults = false;
    
    foreach ( $product_parent_categories_all_hierachy as $ancestor_id) {
        if ( $for_adults->term_id == $ancestor_id) {
            $parent_is_adults = true;
            break;
        }
    }
    
    
    if ( is_product_category( 'adults' ) || $parent_is_adults) {
    
        echo '<img src="'.$image_src.'" alt="'.get_the_title().'" class="product-image blur" title="'.get_the_title().'">';
    
    } else {
    
        echo '<img src="'.$image_src.'" alt="'.get_the_title().'" class="product-image" title="'.get_the_title().'">';
    
    }
    
  2. @0blongCode the code works fine 🙂 but if the debug mode is on, the following notice appears:

    Notice: Undefined variable: category in […] on line […] Notice: Trying to get property of non-object in […] on line […]

    To avoid this we only need to change

    $product_parent_categories_all_hierachy = get_ancestors( $category->term_id, 'product_cat' );
    

    to

    $product_parent_categories_all_hierachy = get_ancestors( $for_adults->term_id, 'product_cat' );
    

Comments are closed.