People frequently want to give something in their blog alternating colors. Most frequently, I’ve seen this question come up when people want the even posts to have a green background (or something) and the odd posts to have a red background (or something). Alternating colors can create a very flattering effect–you may have noticed that your WordPress administration screen uses alternating colors all over the place, especially on the “manage posts” table.
Fortunately, creating alternating colors is a very easy trick is you use just a little PHP. First, an overview.
Overview: What We’re Doing
In most themes, each post gets wrapped in a div that looks something like this:
<div class="post">...</div>The class name might be different, but I have yet to see a theme that doesn’t wrap each post in a div with some class in there. What we want to do is assign an additional class to distinguish even from odd posts. Maybe something like this:
<div class="post even">...</div>
<div class="post odd">...</div>
<div class="post even">...</div>
...Then, in the style.css file, you’ll insert something like this:
.post{ ... the theme author will have put properties here ... }
.odd{background:#f00;}
.even{background:#0f0;}And voila, odd posts are red and even posts are green. To accomplish this trick, we need minimal PHP. Here goes:
How to Do It
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.)
Find the beginning of the loop
. Usually, that looks something like one of these:
<?php if ( have_posts() ) : while( have_posts() ): the_post(); ?>
<?php while( have_posts() ): the_post(); ?>
<?php while( have_posts() ){ ?>Now, just before the loop starts, insert this line of code, exactly as shown, on a line by itself:
<?php $odd_or_even = 'odd'; ?>Now, right after the loop starts, there is probably a <div> wrapper that looks something like this:
<div class="post">.Change that to this:
<div class="post <?php echo $odd_or_even; ?>">Easy so far, right? Now all we need to do is make the class name switch from “odd” to “even” with each post. Just insert this piece of code on the line after the one you just edited:
<?php $odd_or_even = ('odd'==$odd_or_even) ? 'even' : 'odd'; ?>That piece of code may look strange to you. It uses what’s called a ternary operator
, which is just a more concise way of writing this:
<?php
if ('odd' == $odd_or_even){
$odd_or_even = 'even';
}else{
$odd_or_even = 'odd';
}
?>We’re done with the PHP. All you need to do now is add something to your CSS to make the .odd and .even class names look different.