This page is part of my Easy PHP Tutorial for WordPress Users. I'm assuming you already read the tutorial. If not, and something here seems confusing, well... read the tutorial :)
If you came here from the WP forums, please continue asking for support at the forums (rather than posting a comment here). I'm very sluggish at responding to comments on this page.
WordPress users frequently ask how to make their most recent post look different from the rest. Maybe they want to make the font larger, or the background color lighter, or whatever. With a small sprinkling of PHP, this is easy to do. But first, an overview of what we’re trying to accomplish.
Overview of What We’ll Be Doing
What we’re going to do is add a special CSS class to the first post, but not to the others. In most themes, each post gets wrapped in a div that looks something like this:
<div class="post">...</div>We’ll leave that alone for all the posts except the first. For the first, we’ll change that to this:
<div class="post firstpost">...</div>And then it’s a simple matter of defining a background color for the .firstpost class in your style.css, like this:
.firstpost{background:#f00;}So that’s what we want to do. It’s easy with a small amount of PHP.
How to Do It
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.
One comment »
Thank you for this easy to understand explanation! =)
Leave a comment