PHP 循环 : Add a div around every three items syntax

标签 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;

我该如何做到这一点?谢谢!

最佳答案

为什么不执行以下操作?这将打开它并在第三次发布后关闭它。然后在没有显示 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>';

如果您不知道,% 是模数运算符,将返回两个数相除后的余数。

关于PHP 循环 : Add a div around every three items syntax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8947878/

相关文章:

javascript - 动态加密的 Paypal 按钮?

linux - LAMP无法访问WordPress网站

为文件实现伪缓存系统的 PHP 方法

python-3.x - Python - 迭代列表 -Lambda

C++ If Then 不工作/停止

php - 带有哈希标签的 Paypal 返回网址?

PHP imagecreate() PNG 来自任何常用的文件格式?

php - 如何编辑使用 json_decode() 创建的 PHP 对象?

php - 未捕获的 ArgumentCountError。分解意义

javascript - 合并 JQuery 中的字段重置