I am trying to make a custom loop that will display the latest 5 posts from select categories, all using a single query. I want the loop to display the category name followed by the 5 posts, and then the next category, etc.
I followed this answer and it seems to do what I want, except it doesn't output the categories properly.
For example, let's say I want to display categories 100,101,102 and 103, it should display like this:
100
Post 1
Post 2
Post 3
Post 4
Post 5
101
Post 1
Post 2
Post 3
Post 4
Post 5
etc.
The Problem
However, currently, if there is a post in category 100, and also in category 250, it will also display the title of category 250 too, like so
250
Post 1
How do I get it that it ONLY displays the categories specified?
Here's the code I have so far, based on this.
<?php
$args = array(
'posts_per_page' => -1,
'tax_query' => array(
array(
// arguments for your query
'taxonomy' => 'category',
'field' => 'id',
'terms' => $selected_categories, // $selected_categories contains an array of post IDs.
)
)
);
$query = new WP_Query($args);
$q = array();
while ( $query->have_posts() ) {
$query->the_post();
$a = '<a href="'. get_permalink() .'">' . get_the_title() .'</a>';
$categories = get_the_category();
foreach ( $categories as $key=>$category ) {
$b = '<a href="' . get_category_link( $category ) . '">' . $category->name . '</a>';
}
$q[$b][] = $a; // Create an array with the category names and post titles
}
/* Restore original Post Data */
wp_reset_postdata();
foreach ($q as $key=>$values) {
echo $key;
echo '<ul>';
foreach ($values as $value){
echo '<li>' . $value . '</li>';
}
echo '</ul>';
}
?>
Thanks for any help!