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

问题描述 投票:0回答:1

我想在单个查询中从两种不同的帖子类型获取数据,这两种帖子类型具有不同的参数。我正在使用以下代码,但如何在单个查询中合并两个结果?

    $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 );
php wordpress
1个回答
8
投票

您有两个选择,要么合并结果,要么运行第三个查询。我总是喜欢后者,因为这样您可以将查询对象保留在适当的位置,这对于帖子计数器和分页非常有帮助。

我们需要在这里保持聪明,因为这确实会不必要地减慢速度,并且可能变得相当昂贵,所以这就是我们要做的

  • 使用

    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
}
© www.soinside.com 2019 - 2024. All rights reserved.