0

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:

<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.

  • 1
    Have you read this? – fuxia Nov 12 '12 at 18:35
  • I know that it doesn't make sense, my original was written in this way but not working at all: $i++; if(($i % 2) == 0) : $wp_query->next_post(); else : the_post(); In this way it is working a 50%. – Mark Nov 12 '12 at 18:39
2

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) :  ?>
  • Damn, I was so near the solution....thank you this fixed my problem. Thank you very much answer accepted. – Mark Nov 12 '12 at 18:54
  • Don't forget to unset the var at the end. Else you're left with a global of $i and a lot of possible unexpected results... – kaiser Nov 12 '12 at 18:55
1

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
    }
}

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.