WordPress Alternating Classes

It’s often very useful to have alternating classes in for styling purposes. Let’s say you want every other row to be a darker shading, this is very common and I’ll show you how to implement this in WordPress using a simple bit of code.

For my example here I will show you how to create alternating classes for use with the WordPress loop. This way, when the loop pulls your posts from the db every post container will have a separate class name up to as many as we define in our array. This method of alternating classes in WordPress will work for wherever you have a loop. Therefore, your comments, categories, tags, etc. can all be styled up using this method. Pretty cool huh? Let’s see how this is done.

First Define the Class Array

The bit of code below should NOT be inside your WordPress loop, rather right before it.

[code lang=”php”]
// let’s setup some classes first for us to style
$style_classes = array(‘dloccBox1′,’dloccBox2′,’dloccBox3’);
$style_index = 0;

Next Echo the Classes

Now that we have our array setup it’s time to output the class names into the loop

[code lang=”php”]
<?php query_posts(‘category_name=portfolio&order=asc&nopaging=true’); ?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<div class=”<?php $k = $style_index%3; echo “$style_classes[$k]”; $style_index++ ?>”>
<?php the_content(); ?>
<?php endwhile; else: ?>
<?php endif; ?>

On the third line notice how we are using this bit of code to output a class name and then cycle to the next item in the array? Now you are free to style as you wish! Of course, make sure you test with Firebug that the classes are outputting as you want. Let me know if you have any question by commenting below!