I have a page where the latest posts are displayed from within a specific category.
array(
'posts_per_page' => -1,
'post_status'=>"publish",
'post_type'=>"post",
'orderby'=>"post_date",
'order'=>'DESC',
'cat'=>"5"
)
Within this I would like to only show the latest post for each tag. I don't know if this is possible but I'm hoping I'm wrong.
I have a page where the latest posts are displayed from within a specific category.
array(
'posts_per_page' => -1,
'post_status'=>"publish",
'post_type'=>"post",
'orderby'=>"post_date",
'order'=>'DESC',
'cat'=>"5"
)
Within this I would like to only show the latest post for each tag. I don't know if this is possible but I'm hoping I'm wrong.
Share Improve this question edited Mar 13, 2022 at 9:38 Tony Djukic 2,2574 gold badges18 silver badges34 bronze badges asked Mar 8, 2022 at 13:26 Gareth RobertsGareth Roberts 32 bronze badges 3- 1 You could change your query - instead of getting all the posts in that category, set up a loop of tags, and for each tag, get the latest post in the category that has that tag. The downside is, if the posts have multiple tags, they could be shown multiple times. – WebElaine Commented Mar 8, 2022 at 14:56
- Thanks. Each post is only assigned one tag, so that might work. How would that query look? – Gareth Roberts Commented Mar 8, 2022 at 16:01
- 1 Get an array of tags that have published posts in them, then use a foreach on the tags and run a separate query each time to grab a post with that tag and your desired category. – WebElaine Commented Mar 8, 2022 at 19:46
1 Answer
Reset to default 0I think I've cracked it. So now the latest post for each tag type is now displayed. A bit beyond my coding level but its working.
<?php $args = array(
'type' => 'post',
'orderby' => 'post_date');
$tags = get_tags($args);
foreach($tags as $tag) {
$the_query = new WP_Query( 'tag='.$tag->slug );
if ( $the_query->have_posts() ) {
$the_query->the_post();
$desired_posts[] = get_the_ID(); // all the post IDs stored here.
} else {
// no posts found
}
wp_reset_postdata();
}
$args1 = array(
'post_type' => 'post',
'orderby' => 'date',
'post__in' => $desired_posts,
'posts_per_page' => -1
);
$the_query = new WP_Query( $args1 );
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post(); ?>
<div class="">MY HTML STUFF HERE</div>
<? } } else {
// no posts found
}; ?>