Return to Snippet

Revision: 47667
at June 13, 2011 15:09 by kbrown

Initial Code
Open up your WordPress template folder. You need to open whichever file controls the part of your blog in question. If we’re talking about your main page (we probably are), then you probably want to open index.php. (But if there’s a home.php, open that instead.)

Find the beginning of the loop . Usually, that looks something like one of these:

<?php if ( have_posts() ) : while( have_posts() ): the_post(); ?>
<?php while( have_posts() ): the_post(); ?>
<?php while( have_posts() ){ ?>

Now, just before the loop starts, insert this line of code, exactly as shown, on a line by itself:

<?php $firstClass = 'firstpost'; ?>

Now, go into the loop and find the first <div> after the loop starts. In most themes, it will look something like this:

<div class="post">

The class name might be different, but that’s the general idea. Change it to this:

<div class="post <?php echo $firstClass; ?>">

Easy enough so far, right? There’s one more step we need to take, otherwise every post will get that firstpost class added to it, and we don’t want that. So on the line right after the one you just edited, add this in:

<?php $firstClass = ""; ?>

That’s two quotation marks in a row, just in case it isn’t clear. With that piece of code inserted, you’re all done. For the first post, $firstClass is firstpost, but for later posts, $firstClasswill be blank, so echoing it into the div won’t have any effect.

Initial URL

Initial Description

Initial Title
Wordpress - Add CSS class to latest post

Initial Tags
class, wordpress

Initial Language