How would I get 1 latest post from a query for 5 posts?

So I have a wp_query which is getting the 5 most recent posts from my WordPress site. What I want to do is from within this query, grab the most recent post and show this as a sort of ‘hero’ post, and then take the other 4 posts (could be more than 4 if I change the query at a later date) and show in a list or grid below this hero post.

Here is my query code so far (obviously simplified):

<?php 

$query_args = array(
    "posts_per_page" => "5"
);

$listedPosts = new WP_Query($query_args);

// the loop

if ( $listedPosts->have_posts() ) {
    while ( $listedPosts->have_posts() ) {
        $listedPosts->the_post();
        // loop content for hero post goes here (I need to get the most recent post).
    } 
}

// how would I show the other remaining posts in the query?

?>

3 Answers
3

You can use $current_post property of WP_Query

$query_args = array(
    "posts_per_page" => "5"
);

$listedPosts = new WP_Query($query_args);

// the loop

if ( $listedPosts->have_posts() ) {
    while ( $listedPosts->have_posts() ) {
        $listedPosts->the_post();
        if ( (int) $listedPosts->current_post === 0 ) {
          // loop content for hero post
        } else {
          // loop content for remaining posts
        }
    } 
}

Leave a Comment