WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

share|improve this question
By the way I have checked the category is been stored by echoing $cat – Mark H Aug 24 '12 at 0:47
up vote 2 down vote accepted

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.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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