• I am using the following code to get the child categories of the category 7:

    <?php $descendants = get_categories(array('child_of' => 7)); ?>
    <?php foreach ($descendants as $child) { ?>
    //do stuff
    <?php } ?>

    What I need is for each child category, to then query the posts of that category and display the title of the three newest posts in that child category – i.e. all this would happen in the ‘do stuff’ part.

    Anybody any ideas?
    Thanks in anticipation!

Viewing 3 replies - 1 through 3 (of 3 total)
  • Hi

    I didn’t test the code below but it will be close, if not exact

    <?php $descendants = get_categories(array('child_of' => 7)); ?>
    <?php foreach ($descendants as $child) { ?>
           $catPosts = new WP_Query();
           $catPosts->query("showposts=3&cat=$child->term_id"); ?>
           <ul>
           <?php while ($catPosts->have_posts()) : $catPosts->the_post(); ?>
            <li><a href="<?php the_permalink() ?>"<?php the_title(); ?></a></li>
          <?php endwhile; ?>
          </ul>
    <?php } ?>
    Thread Starter equaldesign

    (@equaldesign)

    Thanks for that stvwlf it was almost as required, but thanks to that code I was able to adjust slightly to get what I required which is below:

    <?php $descendants = get_categories(array('child_of' => 7)); ?>
    <?php foreach ($descendants as $child) { ?>
    <?php $catPosts = new WP_Query(); $catPosts->query("showposts=3&cat=$child->term_id"); ?>
    <h2><?php echo $child->cat_name; ?></h2>
    <?php while ($catPosts->have_posts()) : $catPosts->the_post(); ?>
    <ul>
    <li><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></li>
    </ul>
    <?php endwhile; ?>
    <?php } ?>

    equaldesign,
    Thank you for sharing your solution – it was EXACTLY what I needed. I’ve been trying to wrangle the PHP and have come close to a solution but this totally did the trick.

    Thanks again!

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Loop inside sub categories loop’ is closed to new replies.