I'm using a loop in wordpress to output posts. I want to wrap every three posts inside of a div. I want to use a counter to increment on each iteration of the loop but I'm not sure of the syntax that says "if $i is a multiple of 3" or "if $i is a multiple of 3 - 1".
$i = 1;
if ( $wp_query->have_posts() ) : while ( $wp_query->have_posts() ) : $wp_query->the_post();
// If is the first post, third post etc.
if("$i is a multiple of 3-1") {echo '<div>';}
// post stuff...
// if is the 3rd post, 6th post etc
if("$i is a multiple of 3") {echo '</div>';}
$i++; endwhile; endif;
How do I make this happen? thanks!
Why not do the following? This will open it and close it after the third post. Then close the ending div in the event there is not a multiple of 3 to display.
$i = 1;
//added before to ensure it gets opened
echo '<div>';
if ( $wp_query->have_posts() ) : while ( $wp_query->have_posts() ) : $wp_query->the_post();
// post stuff...
// if multiple of 3 close div and open a new div
if($i % 3 == 0) {echo '</div><div>';}
$i++; endwhile; endif;
//make sure open div is closed
echo '</div>';
In case you didn't know, %
is the modus operator will return the remainder after the two numbers are divided.
Use the modulus operator:
if ( $i % 3 == 0 )
In your code you can use:
if($i % 3 == 2) {echo '<div>';}
and
if($i % 3 == 0) {echo '</div>';}
$i = 1;
$post_count=$wp_query->found_posts;
//added before to ensure it gets opened
echo '<div>';
if ( $wp_query->have_posts() ) : while ( $wp_query->have_posts() ) : $wp_query->the_post();
// post stuff...
// if multiple of 3 close div and open a new div
if($i % 3 == 0 && $i != $post_count) {echo '</div><div>';} elseif($i % 3 == 0 && $i == $post_count){echo '</div>';}
$i++; endwhile; endif;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With