2013-10-10 36 views
6

有沒有辦法讓一些WordPress的循環代碼中的項目:WordPress的循環 - 如何計算項目

<?php while (have_posts()) : the_post(); ?> 

這個循環列出的職位。 我需要添加某些類到前3個,取決於它們的總數。

回答

13

您可以使用$WP_Querypost_count property,像這樣:

$wp_query->post_count 

注意與found_posts區別,這計數這雖然匹配查詢,也未顯示的職位(如分頁的)。您可能需要根據您的特定情況使用其中一種。

+0

謝謝兩位的答案。這一個更接近我所需要的。也許我不夠精確。無論他們有多少人,我都需要一些物品。然後,如果總計<3,我需要將類添加到前3或更少 - 但這不應該是問題的一部分。 –

+0

你也可以使用'$項目=計數($個)'如果你想在:) –

+0

現貨! 'found_posts'是我的一個。謝謝! – daneczech

12

這裏是去了解的一種方式:

<?php 
$count = 0; //set up counter variable 
while (have_posts()) : the_post(); 
$count++; //increment the variable by 1 each time the loop executes 
if ($count<4) { 
    // here put the special code for first three 
} 
// here put the code for normal posts 
endwhile; 
?> 
+1

OP需要循環中的帖子總數,而不是當前的索引。 – Sunyatasattva

+1

@Sunyatasattva「我需要某些類添加到第3」 - 他需要計算和測試,如果它小於4特殊類添加到他們... downvote?真? –

+1

就在引用句子後面*「取決於它們的總數」。*他不僅需要將類添加到前三個,這些類將取決於總數。我低估了,因爲這不能回答這個問題。如果您編輯答案以實際解決OP問題,可以始終收回downvote。 – Sunyatasattva