Wordpress - Add CSS class to latest post

/ Published in: PHP
Save to your folder(s)

Copy this code and paste it in your HTML
  1. 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.)
  3. Find the beginning of the loop . Usually, that looks something like one of these:
  5. <?php if ( have_posts() ) : while( have_posts() ): the_post(); ?>
  6. <?php while( have_posts() ): the_post(); ?>
  7. <?php while( have_posts() ){ ?>
  9. Now, just before the loop starts, insert this line of code, exactly as shown, on a line by itself:
  11. <?php $firstClass = 'firstpost'; ?>
  13. Now, go into the loop and find the first <div> after the loop starts. In most themes, it will look something like this:
  15. <div class="post">
  17. The class name might be different, but that’s the general idea. Change it to this:
  19. <div class="post <?php echo $firstClass; ?>">
  21. 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:
  23. <?php $firstClass = ""; ?>
  25. 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.

URL: http://adambrown.info/b/widgets/easy-php-tutorial-for-wordpress-users/first-post-different-from-the-rest/

Report this snippet


RSS Icon Subscribe to comments

You need to login to post a comment.