I need to have an alternating (even, odd…) class on posts to provide alternate highlights on a column. The best thing would be to attach this to the post_class() so that it’s on every instance of post_class(). Below is the code I have at this point to achieve this effect.
<?php
// setting other variables for alternating categories
$style_classes = array('even', 'odd');
$style_counter = 0;
?>
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>
<div class="<?php $k = $style_counter%2; echo $style_classes[$k]; $style_counter++; ?>">
<?php the_cotent(); ?>
</div>
<?php endwhile; ?>
<?php endif; ?>
You should add the following code in
functions.php
:This ensures that all the odd posts on the page will have the class ‘odd’ and all the even posts will have the class ‘even’ just by using
post_class()
in your theme.This works, it passes in the additional class into
post_class()
:EDIT: Here’s a way that creates a version of
post_class()
that will keep track of the count on the page. Now, it will use a new name,oddeven_post_class()
but it does work as you want. All you need to do is drop this intofunctions.php
:So to call it, use
post_class_oddeven()
in your theme wherever you would callpost_class()
I have another solution if you want add a specific class to different content. For instance, only to loop:
Because you don’t want add the “even” or “odd” class when displays a single content.
You can do this with straight forward css. In twentyseventeen theme for example, where the loop is in a div “main”:
will do the trick.