Mr Portman

School website critiques, articles on education and some random cod

Giving posts different classes in the WordPress loop

Tags: ,

Date: 31st October, 2009

For styling purposes it is often useful for posts within a WordPress loop to have a different class. For example, you might want the first post to look different from the others. You can see on the webdev page how the first post includes an image with the text Latest post from the webdev blog. Obviously, I didn’t want this appearing at the top of every post, just the first.

Here’s how I did it:

<?php $postclass = “latestpost”; ?>

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

<!– Give the post’s enclosing <div> the correct class using the variable $postclass… –>

<div class=”<?php echo $postclass; ?>”>

<!– Change the variable $postclass to whatever you want the other posts’ classes to be… –>

<?php $postclass = “recentpost”; ?>

<?php endwhile; ?>

The principle here is to use a variable to style the post and then change the variable for the other posts. For the homepage I took the principle one step further because I needed three different classes:

<?php $classcount = 1; ?>

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

<?php if ($classcount == 1) echo ‘<div class=”lastpost”>’; ?>

<?php if ($classcount == 2) echo ‘<div class=”secondpost”>’; ?>

<?php if ($classcount == 3) echo ‘<div class=”thirdpost”>’; ?>

<?php $classcount++; ?>

<?php endwhile; ?>

You can see here how I used a conditional to check the contents of a variable and return the desired class for the <div> element. The variable is then incrementally increased using $variable++. Works a treat!

September 2010

August 2010

July 2010

June 2010

May 2010

April 2010

February 2010

January 2010

December 2009

November 2009

October 2009

September 2009