2012-01-20 42 views
15

我在wordpress中使用循环来输出帖子。我想要将每三个职位包装在一个div中。我想在循环的每次迭代中使用计数器递增,但我不确定“如果$ i是3的倍数”或“如果$ i是3 - 1的倍数”的语法。PHP循环:围绕每三个条目添加div

$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; 

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

+0

如果我想加入,只有当它超过3项,会发生什么?当它等于3个项目时,不做任何更改? – 2013-09-08 15:14:05

+0

这是我可以找到的最简单的方法:http://stackoverflow.com/questions/28247770/loop-through-wordpress-posts-and-wrap-each-x-post-in-a-div –

回答

44

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

如果你不知道,%是作案运营商将返回剩下的两个数字被划分之后。

+0

看起来不错 - 在速度或效率方面使用其中一个还是有优势的?我认为使用模数运算符可以减少一行代码 –

+0

现在我明白了 - 如果没有3的倍数,使用模将创建一个未关闭的div。谢谢! –

+1

我更喜欢这样,因为它确保关闭所有开放'divs'。我实际上做的是取第一个div并在循环外回显。那样,即使只有1个,你有一个打开/关闭标签。这将确保你不会杀死格式。它的实际处理应该不会影响速度,因为它是一个“基本”方程。 – kwelch

9

使用modulus操作:

if ($i % 3 == 0) 

在你的代码可以使用:

if($i % 3 == 2) {echo '<div>';} 

if($i % 3 == 0) {echo '</div>';} 
+0

你能否请帮忙我把它放在上面我回答的代码的上下文中? –

+0

@ j-man86:你可以使用它已经是,替换'“$ i是'$ i%3 == 0'的3-1的倍数'' –

+0

@ j-man86:请参阅我的更新。 –

0

如果你不需要额外的div你可以使用这个:

$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;