PHP循环:每三个项目语法添加一个div [英] PHP loop: Add a div around every three items syntax
问题描述
我在wordpress中使用循环来输出帖子.我想将每三个帖子都包装在一个div中.我想使用一个计数器在循环的每次迭代中递增,但是我不确定如果$ i是3的倍数"或如果$ i是3-1的倍数"的语法. /p>
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!
推荐答案
为什么不执行以下操作?这将打开它,并在第三篇文章后将其关闭.如果没有要显示的3的倍数,请关闭结尾的div.
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.
这篇关于PHP循环:每三个项目语法添加一个div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!