2013-07-15 189 views
0

我希望有人可以幫助我解決這個問題。我想添加一個自定義帖子類型(證詞)到我的WordPress循環,並顯示一個每幾個職位。我使用pre_get_posts動作將自定義帖子類型添加到循環中,並且它們顯示在循環中,但是我想通過帖子分散這種帖子類型,而不是將它們放在一起。有沒有辦法做到這一點?任何幫助,將不勝感激。添加自定義帖子類型每個幾個帖子

回答

1

如果我正確地閱讀它,你會得到一個查詢,它既獲得了常規的帖子,也獲得了自定義的帖子類型的褒獎。所以從理論上講,你可以根據你的搜索條件抽出10個結果,所有這些結果都是帖子或者所有這些結果將是推薦。

你可能想要做的是做兩個查詢,一個用於文章,一個用於推薦。這會給你兩個post對象的數組,然後很容易循環顯示一個類型或另一個類型,這取決於遞增的計數器。

大致來說,是這樣的:

$args = array('post_type'=>'post', 'posts_per_page'=>9, 'category_name'=>'news); 
$posts = get_posts($args); 

$args = array('post_type'=>'testimonials', 'posts_per_page'=>3); 
$testimonials = get_posts($args); 

/** see how many of the regular posts you got back */ 
$post_count = count($posts); 
/** see how many testimonials you got back */ 
$testimonial_count = count($testimonials); 
/** add them up to get the total result count */ 
$total_count = $post_count + $testimonial_count; 

/** Loop through the total number of results */ 
for($i = 1; $i <= $total_count; $i++){ 

/** assuming you want to show one testimonial every third post */ 
if($i % 3 == 0){ 
    /** this means you're on the a third post, show a testimonial */ 
    setup_postdata($testimonials[$i]); 
} 
else{ 
    /** show a regular post */ 
    setup_postdata($posts[$i]); 
} 

/** and now handle the output */ 
?><h1><?php the_title();?></h1><?php 

} 

在這個例子中它拉一共有12個職位 - 9個員額和3個推薦 - 然後顯示一個見證每一個後第三。假設你實際上每個人都有正確的人數。如果您只收到兩封推薦信,您會得到一個錯誤信息,因此您需要在三元運營商之後使用一些代碼完成該生產網站,以確保有匹配的證明,並且如果不顯示常規帖子等,但應該讓你朝着正確的方向前進。

+0

你好,謝謝你的回答。我試圖實現這個沒有運氣。我只有一個帖子重複了11次。 –

相關問題