2012-01-20 47 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;