0

To assign different classes to every 2nd post in blog view in WordPress adding this code into function.php was suggested as solution. Most people claim it is helpful, but to me it just adds odd at the end of the post class. There is no even class anywhere.

function alternating_post_class($classes) {
    global $wp_query;
    $classes[] = ( $wp_query->current_post%2 === 0 ? 'odd' : 'even' );
    return $classes;
}
add_filter('post_class', 'alternating_post_class');

What have I done wrong? It is suposed to add odd class to my first blog post, then even class for my second post in the blog view, but the result is as I said always the same: odd.

1
  • 1
    Are you using a custom query? Mar 12, 2015 at 20:51

1 Answer 1

2

Give this a try?

function oddeven_post_class ( $classes ) {
   global $current_class;
   $classes[] = $current_class;
   $current_class = ($current_class == 'odd') ? 'even' : 'odd';
   return $classes;
}
add_filter ( 'post_class' , 'oddeven_post_class' );
global $current_class;
$current_class = 'odd';

and be sure you're using <?php post_class(); ?>

5
  • Unfortunately, I put it like this in function.php. And it gives only odd at the end of post class. Again, not 'even' for the second, fourth, sixth...post. :( Mar 12, 2015 at 20:35
  • I tried it here and it works... can you post the code you're using to show the posts?
    – Sarah
    Mar 12, 2015 at 20:37
  • It is Avada default shortcode for Blog. It is in wp-content/plugins/fusion-core/shortcodes/class-blog.php. Too big to post here. Is it maybe that this do not work with Avada shortcodes? Mar 12, 2015 at 20:40
  • <article id="post-<?php the_ID(); ?>" class="<?php post_class(); ?>"> <?php the_permalink() ?> </article>
    – Sarah
    Mar 12, 2015 at 20:40
  • I'm not familiar with that theme or short code. Above is the code you can place inside the loop and it will generate even/odd CSS classes.
    – Sarah
    Mar 12, 2015 at 20:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.