Skip to content

Instantly share code, notes, and snippets.

@gregrickaby
Last active November 20, 2022 12:45
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save gregrickaby/6033650 to your computer and use it in GitHub Desktop.
Save gregrickaby/6033650 to your computer and use it in GitHub Desktop.
Even odd classes in WordPress loop
<?php
// WP_Query Arguments
$args = array(
'order' => 'DESC',
'posts_per_page' => 5
);
// The Loop
$query = new WP_Query( $args );
while ( $query->have_posts() ) : $query->the_post();
// The count (must be inside the loop)
$count++;
$even_odd_class = ( ($count % 2) == 0 ) ? "even" : "odd";
?>
<div class="<?php echo $even_odd_class; ?>">
<p>Some content</p>
</div>
<?php endwhile; wp_reset_postdata(); ?>
@chrismccoy
Copy link

you can avoid your counter and do

 $even_odd_class = $wp_query->current_post % 2 == 0 ? 'even' : 'odd';

@jpjuliao
Copy link

thanks

@reulrich
Copy link

This is a super example, and also works wonderfully. But now I would like to have this Even and Odd in the standard Worpress loop, so here:

if( have_posts() ):
while( have_posts() ) : the_post();

is this possible? If so, is it also possible to add a second class for even and odd?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment