首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在WP_Query中,每个帖子类型都有不同的选项

在WP_Query中,每个帖子类型都有不同的选项
EN

Stack Overflow用户
提问于 2020-11-10 16:22:54
回答 1查看 36关注 0票数 0

我有两种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。

代码语言:javascript
复制
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;
} 
EN

回答 1

Stack Overflow用户

发布于 2020-11-11 20:05:58

我现在已经找到了自己的解决方案,我想在这里分享。

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

代码语言:javascript
复制
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;

}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64765228

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档