Styling the First Post Differently
You’ve got your WordPress site up and running with a theme that you like but one thing is missing. You want the first post on one of your pages to look a little different from the other posts. You know what template file needs changing and you know what The Loop looks like but you’re not sure how to code this.
Well, it’s actually pretty simple. All you’re going to do is add a simple counter to The Loop and output a new CSS class to the first post only.
A basic Loop looks like:
<?php if (have_posts()) :while (have_posts()) : the_post(); ?>
<div <?php post_class();?> id="post-<?php the_ID();?>">
<!-- do the usual post stuff -->
</div>
<?php endwhile; endif; ?>
and the HTML output that it creates on the final page will include:
<div class="post-1234 post type-post status-publish format-standard hentry category-uncategorized single">
The function that outputs all of those classes is post_class() and as you’ll see from the function’s documentation, you can use it to add your own class to a post — which is what you’re about to do.
The amended Loop code would look something like:
<?php $count = 0;
if (have_posts()) :while (have_posts()) : the_post();
$count++;
if( $count == 1 ) $style = ' first-post';
else $style = '';
?>
<div <?php post_class($style);?> id="post-<?php the_ID();?>">
<!-- do the usual post stuff -->
</div>
<?php endwhile; endif; ?>
$count is our post counter which is initially set to zero. $count++; increments the count by 1 each time The Loop “loops”.
if( $count== 1 ) $style = ' first-post';
else $style = '';
These lines checks the current value of $count. If it’s set to 1, then its sets the $style variable to first-post. Otherwise $style is empty. This new custom style variable can then be added to $post_class(). The end result on the final generated page looks like:
<div class="post-1234 post type-post status-publish format-standard hentry category-uncategorized single first-post">
See the extra first-post class? You can now use this new class in your theme’s CSS to apply different formatting to your first post.
Want To Take It Further?
You could use this same technique to apply different styling to every post on a page with only a small change:
<?php $count = 0;
if (have_posts()) :while (have_posts()) : the_post();
$count++;
$style = ' post-number-' . $count;
?>
<div <?php post_class($style);?> id="post-<?php the_ID();?>">
<!-- do the usual post stuff -->
</div>
<?php endwhile; endif; ?>
This will create a new class for every post – post-number-1, post-number-2, post-number-3 etc. The rest is all down to your CSS skills.

FlipFlop 3.0