Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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?

?>
share|improve this question
add comment

3 Answers

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
        }
    } 
}
share|improve this answer
add comment

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.

share|improve this answer
add comment

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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