Customized first post techniques

There doesn’t seem to be a standard technique for differentiating first/top posts. After looking around, I found this method:

$current_query = new WP_Query('post_type=current&post_status=publish'); 

// Pull out top/first post
$first_post = ( $paged == 0 ) ? $posts[0]->ID : '';

while ($current_query->have_posts()) : $current_query->the_post();

if ($first_post == $post->ID) {
    echo '<div class="post top-post-special" id="post-' . get_the_ID() . '">';
} else {
    echo '<div class="post" id="post-' . get_the_ID() . '">';
}

This relies on $paged (which seems to be a WordPress built-in) to add the “top-post-special” class in first post as expected. However, when using the following query_post instead of a new WP_Query instance, it no longer works:

$args=array(
          'taxonomy' => 'highlights',
            'term' => 'Featured',
          'post_type' => 'highlights',
        );

query_posts($args); 

$first_post = ( $paged == 0 ) ? $posts[0]->ID : '';         

if ( have_posts()) : while (have_posts()) : the_post();                 

if ($first_post == $post->ID) {
    echo '<div class="post top-post-special" id="post-' . get_the_ID() . '">';
} else {
    echo '<div class="post" id="post-' . get_the_ID() . '">';
}

I thought the second would be analogous to the first, not sure what I’m doing wrong here. Is there a better or standardized way to target the first post? Seems like this would come up a lot.

3 Answers
3

You shouldn’t need to do any special queries for this. Here is one way to accomplish it

/**
 * conditional check ensures special class only shows on top post on first page.
 * if you want top post on page 2, etc. to have special class, just set $first_post to true
 */
if( (int) get_query_var( 'paged' ) > 1 ){
    $first_post = false;
} else {
    $first_post = true;
}

if ( have_posts()) : while (have_posts()) : the_post();                 

if ( $first_post ) {
    echo '<div class="post top-post-special" id="post-' . get_the_ID() . '">';
    $first_post = false;
} else {
    echo '<div class="post" id="post-' . get_the_ID() . '">';
}

Leave a Comment