[英]Display posts from WP Query and every 4 posts, display 4 posts with taxonomy
我需要幫助創建一個查詢,該查詢顯示來自自定義帖子類型的帖子,每 4 個帖子顯示 4 個包含同一帖子分類的帖子
我應該做兩個不同的查詢嗎? 正常分類:
$args = array( 'post_type' => 'news', 'posts_per_page' => -1, ); $news = new WP_Query($args);
分類查詢:
$args = array( 'post_type' => 'news', 'offset' => 4, 'tax_query' => array( array( 'taxonomy' => 'news-category', 'field' => 'slug', 'terms' => 'the-community', ), ), ); $community = new WP_Query($args);
我不知道如何迭代以獲得我想要的查詢
您需要在循環中使用迭代。 然后在該循環內運行另一個查詢以循環第二組帖子,每次迭代計數器使用模運算符被 4 整除。 每次運行時通過將迭代計數器除以 4 來偏移第二個查詢。
我還沒有測試以下代碼是否可以正常工作,但從概念上講它應該是有效的。
[已編輯]
$args = array(
'post_type' => 'news',
'posts_per_page' => -1,
);
$news = new WP_Query($args);
// Get Loopy
if ( $news->have_posts() ) {
$i = 0; // Set iteration to 0
while ( $news->have_posts() ) {
$news->the_post();
$i++; // Increment iteration counter
// News post output
echo the_title();
// Check if iteration counter is evenly divisible by 4 using the modulo operator (%).
if ( $i % 4 == 0 ) {
$posts_per_page = 4;
// Get your offset.
$offset = $i - $posts_per_page;
$args = array(
'post_type' => 'news',
'posts_per_page' => $posts_per_page,
'offset' => $offset,
'tax_query' => array(
array(
'taxonomy' => 'news-category',
'field' => 'slug',
'terms' => 'the-community',
),
),
);
$community = new WP_Query($args);
while ( $community->have_posts() ) {
$community->the_post();
// Community post output
echo the_title();
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.