Wordpress:WP_Query中每种帖子类型的不同选项

问题描述

我有两种职位类型(A型和B型)和两种分类法(tax-1和tax-2),都分配给每种职位类型。这意味着类型A的帖子可以包含tax-1和tax-2的字词,类型B的帖子也可以包含tax-1和tax-2的字词。

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

我已经尝试为此创建两个$ 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','terms'    => array(21,22,23),);

    return $args;
} 

解决方法

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

这个想法是为两种帖子类型中的每一种创建一个查询。对于每种帖子类型,我将使用wp_list_pluck()在带有帖子ID的列表中得到结果。使用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','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;

}