首页 > 解决方案 > Wordpress:WP_Query 中每种帖子类型的不同选项

问题描述

我有两种帖子类型(A 型和 B 型)和两种分类法(tax-1 和 tax-2),都分配给每种帖子类型。这意味着来自 type-A 的帖子可以包含来自 tax-1 和 tax-2 的术语,来自 type-B 的帖子也可以包含来自 tax-1 和 tax-2 的术语。

我希望我的 WP_Query 输出来自 type-A 的所有帖子,其中包含某些 tax-1 条款。但我不想输出包含这些 tax-1 条款的 B 类帖子,不幸的是,我的 WP_Query 就是这样做的。这同样适用于 tax-2,即只有包含 tax-2 术语的类型 B 的帖子才应该输出。

我已经尝试为此创建两个 $args,但我没有设法合并这两个 $args。

function my_function($args) {
    global $post;

    $args = array(
            'post_type' => array('type-A','type-B'),
            'tax_query' => array(
                'relation'  => 'OR',
                 array(
                    'taxonomy' => 'tax-1',
                    'field'    => 'term_id',
                    'terms'    => array(11, 12, 13),
                ),
                array(
                    'taxonomy' => 'tax-2',
                    'field'    => 'term_id',
                    'terms'    => array(21, 22, 23),
                ),
            ),
        );

    return $args;
} 

标签: phpwordpressargs

解决方案


我现在自己找到了一个解决方案,我想在这里分享。

这个想法是为两种帖子类型中的每一种创建一个查询。对于每种帖子类型,我将在一个列表中获得结果,其中帖子 ID 使用wp_list_pluck(). 随着array_merge()我将列表合并为一个,它可以包含在最终查询中post__in

function my_function($query_args) {
    global $post;
    
    
    $query_args_1 = new WP_Query(array(
            'post_type' => array('type_A'),
            'tax_query' => array(
               'relation'   => 'OR',
                array(
                    'taxonomy' => 'tax_1',
                    'field'    => 'term_id',
                    'terms'    => array(11, 12, 13),
                ),
            ),
));
        $list_id_1 = wp_list_pluck( $query_args_1->posts, 'ID' );
        
        $query_args_2 = new WP_Query(array(
            'post_type' => array('type_B'),
            'tax_query' => array(
                'relation'  => 'OR',
                 array(
                    'taxonomy' => 'tax_2',
                    'field'    => 'term_id',
                    'terms'    => array(21, 22, 23),
                ),
            ),
));
        $list_id_2 = wp_list_pluck( $query_args_2->posts, 'ID' );
        
        $merged_list = array_merge($list_id_1, $list_id_2);
        
        $query_args = array(
            'post_type' => array('type_A', 'type_B'),
            'orderby'   => 'relevance',
            'order'     => 'ASC',
            'post__in'  => $merged_list
);

    return $query_args;

}

推荐阅读