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...
2 Answers
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() ){
the_post();
if( $wp_query->current_post % 2 ){
echo 'right';
} else {
echo 'left';
}
}
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>
<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>
</div>
</div>
<?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>
<div class="col-sm-5 wow fadeInRight" data-wow-duration="500ms" data-wow-delay="300ms">
<?php the_post_thumbnail(); ?>
</div>
</div>
<?php endif; ?>
<?php endwhile; ?>
<!-- Do other stuff... -->
</div>
</div>
</section>
<!--/#features-->
float: right
orfloat: left
according the class set via the result of the modulustwentyeleven
would be great keyword to search for