我有两种post类型( type -A和type-B)和两个分类(tax-1和tax-2),这两种分类都分配给了每种post类型。这意味着来自类型A的帖子可以包含来自tax-1和tax-2的术语,来自类型B的帖子也可以包含来自tax-1和tax-2的术语。
我希望我的WP_Query输出类型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;
} 发布于 2020-11-11 20:05:58
我现在已经找到了自己的解决方案,我想在这里分享。
其思想是为这两种帖子类型中的每一种类型创建一个查询。对于每个帖子类型,我将使用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',
'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;
}https://stackoverflow.com/questions/64765228
复制相似问题