1

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?

?>
6

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

Changing your query args to something like below will order your posts by modified date.

$query_args = array(
    "posts_per_page" => "5",
    "orderby" => "modified",
    "order" => "DESC"
);

You can then use a simple if else condition within the loop and print the first post as a hero and the remaining below it.

0

A simple boolean trigger will do the job.

<?php 

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

$listedPosts = new WP_Query($query_args);

// the loop

if ( $listedPosts->have_posts() ) {
    $first_post = true;
    while ( $listedPosts->have_posts() ) {
        $listedPosts->the_post();
        if( $first_post ) {
            $first_post = false;
            echo '<div class="post first">';
                // loop content for hero post goes here (I need to get the most recent post).
            echo '</div>';
        } else {
            echo '<div class="post">';
                // Rest of the posts.
            echo '</div>';
        }
    } 
}
?>

Then use the .post.first class to style things differently. You can also load in different content, different order/classes on the content, different image sizes, etc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.