So, I have 2 loops, one inside the other. The first to get the category titles, the second to display a few recent post from that category.

Problem: Category titles display fine, but the recent post for each category are the same.

What I end up with is this:

Category-1 Post-1, Post-2, Post-3

Category-2 Post-1, Post-2, Post-3

Category-3 Post-1, Post-2, Post-3



$catArgs = array(
'orderby' => 'name',
'order' => 'ASC',
'exclude' => '106'

$postArgs = array(
'orderby' => 'date',
'order' => 'DESC',
'showposts' => '4',

$categories = get_categories($catArgs);
foreach($categories as $category) {
        $my_query = new WP_Query($postArgs); ?>
            <div class="panel"><span style="font-size: 18px; font-weight: bold;"><a href="<? echo get_category_link( $category->term_id );?>" title="<? echo $category->cat_name; ?>"><? echo $category->cat_name; ?></a></span>
            <div><? echo category_description( $category->term_id ); ?></div>
            <ul class="large-block-grid-4">
                <?php while ($my_query->have_posts()) : $my_query->the_post(); ?>
                        <li><? the_post_thumbnail(); ?><a href="<?php the_permalink() ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></li>
                <?php endwhile; ?>
<? } ?>
<? } ?>


1 Answer 1


You are passing the same arguments to retrieve every set of posts. You have alter the arguments dynamically to reflect the current category.

$categories = get_categories($catArgs);
    foreach($categories as $category) {
        $postArgs['cat'] = $category->cat_ID;
        $my_query = new WP_Query($postArgs);
        // ...

Untested, and I am away from my dev server but that should be pretty close. You will have overlap for recent posts if several show up in multiple categories and I would suggest passing an ignore_sticky_posts argument to WP_Query as well.

  • +1. Also: wp_reset_postdata() would be appropriate here as well. Nov 17, 2013 at 18:51
  • wp_reset_postdata after the foreach loop would be more appropriate. wp_reset-postdata inside the foreach would be overkill as $my_query->the_post(); take care of the same things.
    – s_ha_dum
    Jan 1, 2014 at 22:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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