0

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.

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? 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 1

0

I 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
    }; ?>

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.