問題描述

我正在將兩個不同的帖子類型合併到一個循環中的網站上建立一個部分,然後隨機顯示它們。問題是,我很難找到一種方式來限制每個類型的帖子數量。

這是我試過的:

  • 具有多個 Post 類型的一個查詢可以通過一個數組來實現:

    $args = array( 'post_type' => array( 'photos', 'quotes' ), ...
    

    … 但不能限於每個類型的一定數量的帖子。

  • 在運行 WP_Query 之前合併兩個查詢參數數組:

    $photos = array( 'post_type' => 'photos', 'posts_per_page' => 15, 'orderby' => 'rand' );
    $quotes = array( 'post_type' => 'quotes', 'posts_per_page' => 5, 'orderby' => 'rand' );
    
    $args = $photos + $quotes;
    // Also tried array_merge( $photos, $quotes );
    

    沒有運氣這個後一個變量 $quotes 會覆蓋 $photos,只顯示引號。

  • 通過類型轉換合併兩個 WP_Query 對象:

    $photos_query = new WP_Query( $photos );
    $quotes_query = new WP_Query( $quotes );
    $result = (object)array_merge( (array)$photos_query, (array)$quotes_query );
    

… 等等。

我可能直接使用 SQL 查詢數據庫,但是我需要能夠將這兩個單獨的後期類型組合在一個循環中,隨機佈置,並限制為每種類型的一定量的帖子。

謝謝你的幫助!

最佳解決方案

一種方法是自定義使用 posts_clauses 或其他此類過濾器執行的 SQL 查詢。為了找到它們,在”wp-includes/query.php”& C 中搜索 posts_clauses 看到這一行之前的一系列過濾器。這些一起可以自定義查詢的任何部分

您可以做的另一件事是手動合併對象中查詢的帖子

$photos_query = new WP_Query( $photos );
$quotes_query = new WP_Query( $quotes );
$result = new WP_Query();

// start putting the contents in the new object
$result->posts = array_merge( $photos_query->posts, $quotes_query->posts );

// here you might wanna apply some sort of sorting on $result->posts

// we also need to set post count correctly so as to enable the looping
$result->post_count = count( $result->posts );

次佳解決方案

@mridual aggarwal 你的答案是非常好的,但不幸的是,並不是真正的組合 2 wp_query 它只顯示從兩個安排的帖子我的意思是從第一個& 5 從第二個但沒有排序在一個所以我有這個解決方案& 它至少完成了我的自我的目標

<?php
$term = get_term_by( 'slug', get_query_var( 'tag' ), "post_tag" );
$tagslug = $term->slug;
$post_types = get_post_types('','names');
?>
<?php
//first query
$blogposts = get_posts(array(
    'tag' => $tagslug, //first taxonomy
    'post_type' => $post_types,
    'post_status' => 'publish',
    ));
//second query
$authorposts = get_posts(array(
    'bookauthor' => $tagslug, //second taxonomy
    'post_type' => $post_types,
    'post_status' => 'publish',
    ));
$mergedposts = array_merge( $blogposts, $authorposts ); //combine queries

$postids = array();
foreach( $mergedposts as $item ) {
$postids[]=$item->ID; //create a new query only of the post ids
}
$uniqueposts = array_unique($postids); //remove duplicate post ids

$posts = get_posts(array(
        //new query of only the unique post ids on the merged queries from above
    'post__in' => $uniqueposts,
    'post_type' => $post_types,
    'post_status' => 'publish',
    ));
foreach( $posts as $post ) :
setup_postdata($post);
?>
// posts layout
<?php endforeach; ?>
<?php wp_reset_postdata();?>

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。