You can use the Modulo Operator in PHP to check if the loop count is odd or even and then assign those elements a CSS class based on that.
$class="listpostsright";
if ($wp_query->current_post % 2 == 0) {
$class="listpostsleft";
}
Things to note:
-
In programming counting begins at 0, so this logic may look a bit
backwards, but it should work. -
You don’t need to a variable to count the loop WordPress has already
provided that in the$wp_query
object. -
And never use
query_posts
usepre_get_posts
instead.
Update:
Here is an example of how to use this in your template.
<?php
// Use pre_get_posts to alter your query.
// This would be done in your functions.php
while (have_posts()) :
the_post();
$class="listpostsright";
if ($wp_query->current_post % 2 == 0) {
$class="listpostsleft";
}
?>
<article id="post-<?php the_ID(); ?>" <?php post_class($class); ?>>
Positioning of your elements here, you should be able to do with css alone. Unless it is much more complex than your example.
</article>
<?php endwhile; ?>