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.

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;
share|improve this question
    
have a look at this answer –  Milo May 3 '11 at 22:00
add comment

2 Answers

up vote 1 down vote accepted

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;
share|improve this answer
    
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 May 3 '11 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 May 4 '11 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 May 4 '11 at 0:32
1  
Works great - nice work! –  Avisra May 4 '11 at 0:33
    
@Avisra - n/p. you're welcome :) –  kaiser May 4 '11 at 1:50
add comment

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.)

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.