PHP loop: Add a div around every three items synta

2019-01-16 16:52发布

问题:

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!

回答1:

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.



回答2:

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>';}


回答3:

$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;


回答4:

if you dont need extra div you can use this :

 $i = 0;

 $post_count = $wp_query->found_posts;

 if ( $wp_query->have_posts() ) : while ( $wp_query->have_posts() ) :$wp_query->the_post();

 // If is the first post, third post etc.
 ( ($i%3) == 0 ) ? echo '<div>' : echo '';

 // post stuff...

 // if is the 3rd post, 6th post etc or after the last element

( $i == ($post_count - 1) || (++$i%3) == 0 )  ? echo '</div>' : 
echo '';

endwhile; endif;