My loop displays posts in two columns using this php
<?php
if (have_posts()): while (have_posts()) : the_post();
$count++;
?>
<?php if ($count == 1) : ?>
<div class="home-ci-row">
<div style="padding: 0px;" class="main-column-item-wrap">
CONTENT OF POST : Title, Thumbnail, Excerpt... etc
</div>
<div class="home-ci-gap"></div><!-- /* the gap */ -->
<?php elseif ($count == 2) : ?>
<div style="padding: 0px;" class="main-column-item-wrap">
CONTENT OF POST : Title, Thumbnail, Excerpt... etc
</div> <!-- main-column-item-wrap -->
</div><!-- /* home-ci-row*/ -->
<?php $count = 0; ?>
<?php else : ?>
WHEN THERE IS NO POSTS
<?php endif; endwhile; endif; ?>
You can see that the div ” opens in the first count & closes in the second one.
so when my loop has an even number of posts works great, but with odd number it doesn’t close the div
so My idea is this:
If loop has even number
http://i.stack.imgur.com/Hu4Ua.png
If loop has odd number of posts
http://i.stack.imgur.com/JjqzZ.png
I hope my question is clear,
You could do this much easier. As you are making a layout that can be achieved by floats, there is no need to declare a Row every second time.
In my Code example I just youse the
$count
to determine the Class of the HTML-Element. In combination with the total Number of Posts displayed.If the total number of posts
$wp_query->post_count
is reached by the$count
AND the total number is odd, I give the Element the Classfullwidth
. In the same way, I determine if it is the first or the second (see the IF-Statement).All I need to do afterwards is output the corresponding Class for each HTML-Element in the Loop. Besides the Class, no Element is diffferent from each other.
I use the
Modulo
Operator in PHP (%
) to determine odd/even. It delivers1
if I use$count % 2
and$count
is odd. If you are not sure about this operator, read about it here.So your code could look like this: