2

While inside "the loop" in WordPress, is there an easy way to detect if a post is the most recent? A Usage Example: I want to make the first post output an H1 for the title instead of an H2. Or I want the first post to display a thumbnail image (and not the rest).

Here is some pseudocode what I'm trying to get across:

        if (have_posts()):
            while (have_posts()):
                the_post();
                the_excerpt();
                if(is_most_recent()):
                    // do this
                endif;
            endwhile;
        endif;
1

3 Answers 3

2

In addition to @Milo Answer (this avoids a senseless query, because we already got every needed information from the current wp_query):

if ( have_posts() ) : 
    while ( have_posts() ) : the_post();
        $headline_html_tag = $GLOBALS['wp_query']->current_post === (int) 0 && $GLOBALS['paged'] === (int) 1 ? '1' : '2';
        the_title( '<h'.$headline_html_tag.'><a href="'.get_permalink().'" title="'.the_title_attribute( array( 'before' => 'Permalink to: ', 'after' => '', 'echo' => false ) ).'">', '</a>'.'</h'.$headline_html_tag.'>', false );
    endwhile; 
endif;
5
  • Actually - I just realized something. That will always be true for the first item in the current collection. If you are on page two of the blog, the first item on page two would be assigned the h1 as well. The only way to make it truly the latest item is by doing Chip's method
    – Avisra
    Commented May 3, 2011 at 23:57
  • @Avisra - No. You just have to take advantage off the $GLOBALS['paged'] variable. See edit. Avoiding DB-queries always should be first priority.
    – kaiser
    Commented May 4, 2011 at 0:29
  • Hmm okay - I see the edit. I'll give that a shot in just a minute - thank you. I completely agree on minimizing DB queries - so if this works - it's definitely the best solution
    – Avisra
    Commented May 4, 2011 at 0:32
  • 1
    Works great - nice work!
    – Avisra
    Commented May 4, 2011 at 0:33
  • @Avisra - n/p. you're welcome :)
    – kaiser
    Commented May 4, 2011 at 1:50
3

Try using get_posts()? Codex ref

e.g.:

function is_latest_post() {
    $latestpost = get_posts ( array(
        'numberposts' => 1
    ) );
    $latestpost = $latestpost[0];
    $is_latest = ( $latestpost->ID == get_the_ID() ? true : false );
    return $is_latest;
}

(Must be used within the Loop.)

0

An even easier way is to check if there is a next post. If not, we can assume this is the latest...

$nextPost = get_next_post();
if (empty($nextPost)) {

//This is the latest post

} else { 

//This is not the latest post

}

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.