I am modifying the theme TwentyEleven.

In index.php there is the loop which accesses content.php template:

<?php while ( have_posts() ) : the_post(); ?>

  <?php get_template_part( 'content', get_post_format() ); ?>

<?php endwhile; ?>

The trouble is that I need different formatting (different classes) for odd and even posts. How to do this?

My only idea is to remove content.php and insert the code directly to index.php with variable $i counting the position in the loop (by ++$i). But that's bad.

  • This isn't really a WordPress question. You can use the nth-child CSS selector, or toggle a class outpout variable in PHP. – anu Aug 6 '12 at 8:45
  • @anu But it can be done nicely with wp core functions. – kaiser Sep 26 '12 at 11:56

Open up content.php and replace this:

<?php post_class(); ?>

...with this:

<?php post_class( ++$GLOBALS['wp_query']->wpse60971_current_post % 2 === 0 ? 'even' : 'odd' ); ?>
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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