Change styling for every second post in WordPress

Although WordPress posts usually share the same styling, that doesn’t mean you can’t change the way there are displayed on your homepage. We already showed how easy is to differently style only the first post in your blogroll, but if you’re going for a bigger change, that might not be enough for you.

Depending on what your site is all about, you might want to change the styling of every second post in the loop. Just like you might have styled tables so that every second row is shown in different color, you may also style posts in WordPress differently. Similarly, you can style posts for each author differently.

It doesn’t matter if you want to change the color of post background, change font size or simply indent every second post on the list, we’re about to you show a simple technique of styling your odd and even WordPress posts.

The following function will go through the list of posts found on your website and it will add a specific class to odd and even numbered posts. By doing so, every second post will get a class you can easily style with CSS.

Teach WordPress how to recognize every second post:

  1. Open functions.php
  2. Copy and paste the following:
  3. function style_every_second_post ( $classes ) {
    global $current_class;
    $classes[] = $current_class;
    $current_class = ( $current_class == 'odd' ) ? 'even' : 'odd';
    return $classes;
    }
    add_filter ( 'post_class' , 'style_every_second_post' );
    global $current_class;
    $current_class = 'odd';
    
  4. Save changes

WordPress has just learned how to add a class to different posts, but your work isn’t done. While the function is already doing its job, you still need to define classes which are added to each and every post in the loop. Unless your theme is already using .odd and .even classes, you will have to style ones separately (in case it is, simply change names of classes in the code shown above).

Style every second post differently:

  1. Open style.css file
  2. Add any styling you want. For example:
  3. .odd {
    color: red;
    {
    
    .even {
    color: blue;
    {
    
  4. Save changes
  5. Open your homepage or blogroll to see the changes

If you have used the same style from above, your posts should have text painted in red and blue. Since this was just an example and this would obviously hurt everyone’s eyes, it is up to you to come up with the best style for your website. You don’t even have to change both stylings; it is enough to change one of those to see the difference on your display.

Now that your posts are ordered by their styling, show us your work in comments and let us know why you made the change.

START YOUR OWN BLOG

This guide is an introduction to mastering the art of blogging. It provides easy to follow steps to start, maintain, and grow your blog.

Read the guide

Leave a Reply

Your email address will not be published. Required fields are marked *