2016-02-10 31 views
0

我想有兩個職位type.I不同的參數在一個查詢中獲取來自兩個不同的信息類型的數據合併兩個職位類型正在使用下面的代碼,但我怎麼能在一個組合兩個結果單個查詢?在一個單一的WP查詢

$args = array(
     'post_type' => 'post', 
     'posts_per_page'=> '1', 
    ); 
    $args1 = array(
     'post_type' => 'page', 
     'posts_per_page'=> '3', 
    ); 
    $post_query = new WP_Query($args); 
    $page_query = new WP_Query($args1); 
+0

你需要兩個查詢至少 –

+0

是可以合併'$ posts'性能 –

+0

請檢查一下,我已經更新了我的question.How可以我現在在一個查詢中組合兩個查詢? – Johny

回答

1

您有兩個選擇,可以合併結果或運行第三個查詢。我總是喜歡後者,因爲這樣你就可以保留查詢對象,這對於郵局計數器和分頁非常有用。

我們需要聰明在這裏,因爲這會很慢下來不必要的,可能會變得非常昂貴,所以這就是我們將做

  • 運行兩個很瘦,與get_posts非常聰明的查詢(更優化的作爲一個正常WP_Query因爲它打破分頁這使得它更快)。我們也只是查詢帖子ID而不是全部對象。這將使這些查詢非常快速和非常精簡。它幾乎就像你從來沒有做過這些查詢;-)

  • 一旦我們從這些查詢中得到結果,我們就可以合併ID並運行最終查詢返回完整的post對象,我們可以用它來運行適當的環

讓我們看一下代碼

// Set our defaults to keep our code DRY 
$defaults = [ 
    'fields'     => 'ids', 
    'update_post_term_cache' => false, 
    'update_post_meta_cache' => false, 
    'cache_results'   => false 
]; 
// Set query args for query 1 
$args = [ 
    'post_type'  => 'post', 
    'posts_per_page' => '1', 
]; 
// Set query args for query 2 
$args1 = [ 
    'post_type'  => 'page', 
    'posts_per_page' => '3', 
]; 
$post_query = get_posts(array_merge($defaults, $args )); 
$page_query = get_posts(array_merge($defaults, $args1)); 

// Merge the two results 
$post_ids = array_merge ($post_query, $page_query); //. You can swop around here 

// We can now run our final query, but first mke sure that we have a valid array 
if ($post_ids) { 
    $final_args = [ 
     'post_type' => ['post', 'page'], 
     'post__in' => $post_ids, 
     'orderby' => 'post__in', // If you need to keep the order from $post_ids 
     'order'  => 'ASC' // If you need to keep the order from $post_ids 
    ]; 
    $loop = new WP_Query($final_args); 

    // Run your loop as normal 
}