How can I create a type of loop in WordPress where an image moves left or right for each post? I.e. first post image will be left, second post image will go right, third post image will go left, and so on...

  • Not really WordPress specific. What you need is a counter, modulus operator and variable class according to the result of the modulus, and then CSS which should be something like float: right or float: left according the class set via the result of the modulus – Pieter Goosen Apr 8 '16 at 5:54
  • FYI, there is a tutorial for this, just can't remember where. I know this, because I searched for something similar when I started out. Just put some effort in and do some research, you'll find it. If I remember correctly, the tutorial was done on the twentyeleven theme, so twentyeleven would be great keyword to search for – Pieter Goosen Apr 8 '16 at 5:57

The PHP modulus operator gives you the remainder from dividing 2 numbers. The remainder from the division of any number by two is either 0 or 1, so we can use that to provide an "alternator". We use the current_post var as a counter, which is available in any WP_Query object:

while( have_posts() ){

    if( $wp_query->current_post % 2 ){
        echo 'right';
    } else {
        echo 'left';

| improve this answer | |

Thank You very much. Problem solved. Here is my code.

<section id="features">
    <div class="container">
        <div class="row">
        <?php $args = array(
            'post_type' => 'service',
            'posts_per_page' => 4
        $service = new WP_Query($args);
        while ( $service->have_posts() ) : $service->the_post(); 
            <?php if($service->current_post % 2) : ?>
             <div class="single-features" id="post-<?php the_ID(); ?>"<?php post_class('my-class'); ?>>

                <div class="col-sm-5 wow fadeInLeft imagePosition" data-wow-duration="500ms" data-wow-delay="300ms">
                    <?php the_post_thumbnail(); ?>
                <div class="col-sm-6 wow fadeInRight textPosition" data-wow-duration="500ms" data-wow-delay="300ms">
                    <h2><?php the_title(); ?></h2>
                    <P> <?php the_content(); ?></P>
            <?php else : ?>

             <div class="single-features">
                <div class="col-sm-6 col-sm-offset-1 align-right wow fadeInLeft" data-wow-duration="500ms" data-wow-delay="300ms">
                    <h2><?php the_title(); ?></h2>
                    <P><?php the_content(); ?></P>
                <div class="col-sm-5 wow fadeInRight" data-wow-duration="500ms" data-wow-delay="300ms">
                    <?php the_post_thumbnail(); ?>
    <?php endif; ?>
        <?php endwhile; ?>
            <!-- Do other stuff... -->

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