Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP loop: Add a div around every three items syntax [duplicate]

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!

like image 643
HandiworkNYC.com Avatar asked Jan 20 '12 21:01

HandiworkNYC.com


3 Answers

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.

like image 192
kwelch Avatar answered Nov 03 '22 04:11

kwelch


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>';}
like image 29
George Cummins Avatar answered Nov 03 '22 02:11

George Cummins


$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;
like image 20
Habib Avatar answered Nov 03 '22 04:11

Habib