PHP loop: Add a div around every three items synta

2019-01-16 17:01发布

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!

4条回答
Rolldiameter
2楼-- · 2019-01-16 17:31

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.

查看更多
我想做一个坏孩纸
3楼-- · 2019-01-16 17:34

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;
查看更多
趁早两清
4楼-- · 2019-01-16 17:47

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>';}
查看更多
放荡不羁爱自由
5楼-- · 2019-01-16 17:48
$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;
查看更多
登录 后发表回答