Alternating post layout

I am trying to create a layout with two different divs alternating vertically.
For example the even has to be: picture + content; and the odd has to be: content + picture.

Here is my code, at the moment it prints every post doubled, once per div:

Read More
<div id="content">
<?php if (have_posts()) : while(have_posts()) : $i++; if(($i % 2) == 0) : the_post(); ?>

    <div id="leftcontent_1">
    <a href="<?php the_permalink(); ?>"><img src="<?php echo $image ?>"/></a>
    </div>

    <div id="rightcontent_1">
    <h2><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link: <?php the_title(); ?>"><?php the_title(); ?></a></h2>

    <?php the_content(); ?>
    </div>      
    <div class="clear"></div>

<?php else : ?>

<div id="rightcontent_2">
    <a href="<?php the_permalink(); ?>"><img src="<?php echo $image ?>"/></a>
    </div>

    <div id="leftcontent_2">
    <h2><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link: <?php the_title(); ?>"><?php the_title(); ?></a></h2>

    <?php the_content(); ?>
    </div>      
    <div class="clear"></div>

<?php endif; endwhile; endif; ?>
</div>

Any hint on how can I fix it?

Thank you in advance.

Related posts

Leave a Reply

2 comments

  1. minimal necessary correction – move the_post(); to before the if(($i%2 == 0) :

    for instance:

    <?php if (have_posts()) : while(have_posts()) : the_post(); $i++; if(($i % 2) == 0) :  ?>
    
  2. Built into the query

    Alternating post styles (or classes) are not that hard. The $wp_query object has a current_post property, that you can build upon. Simply do some math with it.

    Example

    A very basic example that checks if we got an even or odd post.

    global $wp_query;
    if ( have_posts() )
    {
        while( have_posts() )
        {
            the_post();
            if ( 0 === $wp_query->current_post %2 )
            {
                // do stuff for even posts
    
                // Jump to next post in the loop
                continue;
            }
            // do stuff for odd posts
        }
    }