WP_Query not looking at child category

Hi all I have a loop that shows a post on a single page and puts the first category name in the variable $cat:

$cat = $category[0]->cat_name;?>

Now after the post I have a link to show related posts based on this category:

$catPosts1 = new WP_Query(array('category_name'=> $cat, 'orderby' => 'rand', 'posts_per_page' => 1));
    while ($catPosts1->have_posts()) : $catPosts1->the_post();

The problem I’m having if a Child Category is selected for the first post I.e. Under the category Phones the child category Accessories is chosen nothing is appearing in the related link area. Is there a way of making WordPress use this child category?
Thanks

1 Answer
1

You’ll have to get the child or parent categories yourself and pass all the IDs as an array via the category__in argument of WP_Query. You can use get_ancestors to get the top parent category, and get all child categories of that parent via the child_of argument of get_categories.

Leave a Comment