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
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="https://wordpress.stackexchange.com/questions/129022/<?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>