to start, i would like to express my thanks and gratitude to all the volunteers in the wordpress forum who patiently and freely give their time and attention, and share their knowledge and experience with all the users coming with questions and problems about their wordpress installation and modifications.
a great community.
lists or posts styled with alternating color backgrounds, for instance, can inprove the readability of blogs.
most themes and the standard wordpress installation are not offering this feature.
however, it is easy to implement, when you know how.
for example we could give alternating posts within the ‘wordpress loop’ a different extra class (‘odd’ or ‘even’) which can then be used with css.
to begin with, we introduce a counter ($c = 0;) before the loop, increment it inside the loop ($c++), and generate a class depending on the number of the counter by checking the modulus 2 of the number ($c % 2 – modulus is the remainder of the division):
<?php $c = 0 ; ?> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <?php $c++; if( $c % 2 == 0 ) $extra_class = ' even'; else $extra_class = ' odd'; ?> <div class="post <?php echo $extra_class; ?>"> <!--typical stuff in the loop--> </div> <?php endwhile; ?> <?php else : endif; ?>
the class ‘odd’ or ‘even’ can be used in the style.css to create different background colors, alignments, margins, paddings, font-styles – no limits.
the most basic application of this method with a counter is how to style the first post in the loop different (only showing the logic part of the code):
<?php $c++; if( $c == 1 ) $extra_class = ' first'; else $extra_class = ''; ?>
to make it more interesting, the next example is to create three different styles and a special style for the last post on the page.
we can get the number of the last post with
The structure is the same, the main difference is in the ‘if, elseif, else’ logic:
<?php $c++; if( $c == $wp_query->post_count ) $extra_class = ' last'; elseif( $c % 3 == 0 ) $extra_class = ' three'; elseif( $c % 3 == 2 ) $extra_class = ' two'; elseif( $c % 3 == 1 ) $extra_class = ' one'; ?>
you can extend this method to create any number of cyclic classes.
EDIT: a new way of adding any number of recursive css classes – without counter variable, using the $wp_query->current_post of a default loop:
$extra_classes = array('one','two','three','four','five'); $extra_class = $extra_classes[$wp_query->current_post%count($extra_classes)]; echo $extra_class;
END OF EDIT
and you can use it in any situation in your wordpress templates, where you loop through some output – lists, foreach, for, while, posts, comments, …
special thanks to @esmi who dared venturing into the realm of more than two alternating styles, and who inspired me to post this article.