在单个WP查询中合并两个帖子类型

时间:2016-02-10 07:19:03

标签: wordpress

我想在一个查询中从两个不同的帖子类型中获取数据,这两个查询对于帖子类型都有不同的参数。我使用下面的代码但是如何在一个查询中组合两个结果?

    $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 );

1 个答案:

答案 0 :(得分:4)

您有两个选项,可以合并结果或运行第三个查询。我总是喜欢后者,因为那样你就可以保留查询对象,这对于帖子计数器和分页很有帮助。

我们需要在这里变得聪明,因为这可以减少不必要的东西并且变得非常昂贵,所以这就是我们将要做的事情

  • 使用get_posts运行两个非常精简,非常智能的查询(更优化为正常WP_Query,因为它打破了分页,使其更快)。我们也只是查询帖子ID而不是完整对象。这将使这些查询非常快速且非常精简。这几乎就像你从未做过那些疑问一样; - )

  • 一旦我们获得了这些查询的结果,我们就可以合并ID并运行最终查询以返回完整的帖子对象,我们可以使用它来运行正确的循环

让我们看一下代码

// 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
}