Posted By

kbrown on 06/13/11


Tagged

class wordpress loop latestPost


Versions (?)

Wordpress - Add CSS class to latest post


 / Published in: PHP
 

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

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

Report this snippet  

You need to login to post a comment.