Han*_*com 20 php wordpress loops while-loop
我在wordpress中使用循环来输出帖子.我想在div中包含每三个帖子.我想在循环的每次迭代中使用计数器递增,但我不确定语法是否"如果$ i是3的倍数"或"如果$ i是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;
Run Code Online (Sandbox Code Playgroud)
我该如何实现这一目标?谢谢!
kwe*_*lch 53
为什么不这样做呢?这将打开它并在第三个帖子后关闭它.然后在没有3的倍数显示的情况下关闭结束div.
$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>';
Run Code Online (Sandbox Code Playgroud)
如果你不知道,%
在两个数字被分割后,modus运算符将返回余数.
Geo*_*ins 10
使用模数运算符:
if ( $i % 3 == 0 )
Run Code Online (Sandbox Code Playgroud)
在您的代码中,您可以使用:
if($i % 3 == 2) {echo '<div>';}
Run Code Online (Sandbox Code Playgroud)
和
if($i % 3 == 0) {echo '</div>';}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
40504 次 |
最近记录: |