2

I have 5 categories. I want to query each category and get a list of the most recent posts from them. I also only want single post from each category, with no duplicates. Is there a way to do this without writing 5 queries? Can it be done with one query?

I should end up with the following results:

1|most recent post from CategoryA
2|most recent post from CategoryB
3|most recent post from CategoryC
4|most recent post from CategoryD
5|most recent post from CategoryE

3

1 Answer 1

2

Here is some code I used for the front page of this site. It pulls one post (I chose a random post) from each category and displays some of the post content. I've included the HTML so you can make sense of it.

<div id="main-content" class="main-content-wide">    
<?php
    //Get the desired categories and order by ID
    $cat_args = array(
    'include' => '7,8,9,10, 14, 60',
    'orderby' => 'ID',
    'child_of' => 0
    );

//For each category show a random post
$categories =   get_categories($cat_args); 
foreach($categories as $category) 
    {
?>        

<div class="categorytitle">    
    <h3>Children's Stories <?php echo $category->name; ?></h3>
    <a href="<?php echo get_category_link( $category->term_id ); ?>" class="allstories"> (More Stories...)</a>
</div>

<div class="story">
    <?php
    $post_args = array(
    'numberposts'   => 1,
    'orderby'   => rand,
    'category'  => $category->term_id
    );

    $posts = get_posts($post_args);
    foreach($posts as $post)    
    {
?>    
//Show post content     
<?php get_template_part('loop'); ?>
</div>
<?php
        }
}
?>   

</div>
1
  • this actually worked great. Thanks for the assist with that. I knows its been awhile, but i finally was able to get back to this project.
    – Robbiegod
    Commented Jan 20, 2015 at 18:54

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.