Sometimes we have a need to highlight the first post in loop of main page, archive page or search page and apply different style for it. This output can be implemented by using special CSS class and simple php code.
Originally we have the regular loop to output our posts:
<?php if (have_posts()) : ?> <?php while (have_posts()) : the_post(); ?> <div class="post"> ... </div> <?php endwhile; ?> <?php endif; ?>
In order to change the style of the first post, the class ‘first’ must be added to it.
<?php $i = 0; ?> <?php if (have_posts()) : ?> <?php while (have_posts()) : the_post(); ?> <?php $i++ ?> <div class="post<?php if ($i == 1) echo ' first'; ?>"> ... </div> <?php endwhile; ?> <?php endif; ?>
Next, using class ‘first’ we can define the rules for class ‘first’.
Simple enough!
Leave a trackback from your own site.
Leave a Reply
You must be logged in to post a comment.
One Response to “Highlight First Post”
This works great but, is there a way of having the first post being highlighted on just the first page only? When you have pagination the second page displays the first post on this page as being highlighted also. Nice work thanks! ;-)