Zebra Stripes in WordPress

Creating a theme where the posts or lists alternate in colour can visually make a blog that little more attractive and can improve its readability as well. So here is a quick way to add a zebra striping effect to a loop within WordPress.

The way this works is with a simple counter within php that is then called within the loop to add a class depending on if the post count is an odd or even number.

The counter gets introduced before the start of the loop like so:

<?php $c = 0 ; ?>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>

The rest of the loop will be created pretty much as normal, the only difference is the addition of class within the container for the post, be that a div or a list item.

<div class="<?php echo $c++&1 ? 'even' : 'odd'; ?>">
... rest of loop  here ....

In combination with the counter that is started before the loop this bit of php will use the classes even or odd depending on if the post is counted as an even or odd number.

All that is left to do is style the classes within the css to however you would like them to look.

.odd {style here}
.even {style here}

Here is an example of a loop fully coded:

<ul class="news">
   <?php $c = 0 ; ?>
      <?php if (have_posts()) : while (have_posts()) : the_post(); ?>
         <li class="<?php echo $c++&1 ? 'even' : 'odd'; ?>">
            <h3><?php the_title(); ?></h3>
            <?php the_excerpt(); ?>
         </li>
      <?php endwhile; ?>
   <?php else : endif; ?>
</ul>

2
Comments

  • Andre
    April 7, 2011 | Permalink |

    Aha…. That is a very nifty trick, definitely going to play around with this one! I’m just getting started with WordPress, so there’s quite a bit I still need to learn. Thanks very much for sharing this.. :D

  • Dizi
    April 7, 2011 | Permalink |

    I’m glad that you have found the post to be of some use Andre :) Good luck with learning WordPress.

Have Your Say

Your email is never shared. Required fields are marked *
To add code to a comment use this [code] your code here [/code]