How to Check if a Child Category is Being Queried

The function cat_is_ancestor_of takes two arguments (two category IDs). To check if category of ID 61 is ancestor of category with 54:

 cat_is_ancestor_of(54,61);

I’m not sure if there is a better way of doing this, but you can get the current category’s ID with the get_queried_object() and then check this an ancestor of the category with some ID (6 in this example):.

function change_number_of_posts($query) {
    if ($query->is_category){
         $cat = get_queried_object();
         $cat_id = (int) $cat->term_id;

         if( $query->is_category('recipes') || $query->is_category('product-reviews')){
              $query->query_vars['posts_per_page'] = -1; 
         }elseif(cat_is_ancestor_of(6,$cat_id)){
              $query->query_vars['posts_per_page'] = -1; 
         }
    }

    return $query;
}

add_filter('pre_get_posts', 'change_number_of_posts'); 

Untested.

(I’ve left out any checking of errors (e.g. in case the category doesn’t exist)).

Leave a Comment