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

  • By the way I have checked the category is been stored by echoing $cat – Mark H Aug 24 '12 at 0:47

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.