簡體   English   中英

在很少的帖子中添加自定義帖子類型

[英]Add Custom Post Type Every Few Posts

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

如果我閱讀正確,那么您會得到一個查詢,該查詢同時收到常規帖子和自定義帖子類型的推薦。 因此,根據您的搜索條件,理論上您可以提取10個結果,這些結果全部是帖子,或者全部是推薦書。

您可能想做的是進行兩個查詢,一個查詢職位,一個查詢推薦。 這將為您提供兩個發布對象數組,然后很容易遍歷並根據遞增的計數器顯示一種或另一種類型。

非常粗略地講,類似:

$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個推薦書-然后每三個帖子顯示一次推薦書。 假設您實際上每個人都有正確的號碼。 如果您只獲得了兩個證明書,那么您將得到一個錯誤,因此,一個生產站點您想在三元運算符之后用一些代碼完成它,以確保有一個匹配的證明書,如果沒有顯示常規的話發布等信息。但是應該讓您朝正確的方向前進。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM