我在 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/