Using Odd Even Classes In Genesis Archives

This PHP code adds odd even classes to your posts in any archive type ( loop ) in any WordPress theme.

add_filter( 'post_class', 'left_right_classes' );
function left_right_classes( $classes ) {

    global $wp_query;
	
    $classes[] = ( $wp_query->current_post % 2 == 0 ) ? 'left' : 'right';
	
    return $classes;
}

Why Unique? #

In this case, the code uses a ternary operator rather than if else statement.

Demo #

In this case, the classes are named left and right to style odd/even posts in this timeline template for Genesis differently.

Code Usage #

You can use this code (1) directly in any archive type template which uses the WordPress Template Hierarchy or (2) in your child themes functions file with a conditional tag so it only runs on specific archives.

Once you add the PHP in your theme and it has executed, it outputs HTML in your source code which shows the new classes added to existing article classes which you can view using your browsers Inspect Element feature.

You can then use these custom classes in your style sheet like this to style each odd/even post :

.left {
    background: blue;
}

.right {
    background: red;
}

Was This Tutorial Helpful?

Free

$0

Access only to all free tutorials per month.



Monthly

$75

Access to 10 premium tutorials per month.


Tutorial Request


Includes code guarantee and coding support.

Yearly

$500

Access to 15 premium tutorials per month.


Monthly Tutorial Request


Includes code guarantee and priority coding support.