While in “the loop”, detect if a post is the most recent

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;

Related posts

Leave a Reply

3 comments

  1. 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;
    
  2. 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.)

  3. 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
    
    }