WordPress函数:WP_Query 使用 tax_query 根据自定义文章分类查询文章

追格官方小助手/ 2022年07月08日/ WordPress/ 浏览 1798

在WordPress开发中,经常需要自定义文章类型和自定义文章分类,那么如何根据自定义文章类型查询文章呢?这就需要使用 WP_Query 的 tax_query 参数了。


tax_query 本身接受一个字符串 relation 和 一个条件数组。relation用来指定条件数组元素之间的逻辑关系,比如 AND 或者 OR;如果条件数组中只有一个条件,relation 应当省略掉。


条件数组中的元素,又包含4个字段:


taxonomy:自定义分类;


field:用来比对的字段-taxonomy数组表中的字段


terms:指定的目标值


operator: filed和terms之间的关系,可以是:‘IN’, ‘NOT IN’, ‘AND’, ‘EXISTS’ and ‘NOT EXISTS’,默认为 ‘IN’。


以下举例说明:


1. 查询自定义分类people下slug为bob的文章


$args = array(
    'post_type' => 'post',
    'tax_query' => array(
        array(
            'taxonomy' => 'people',
            'field'    => 'slug',
            'terms'    => 'bob',
        ),
    ),
);
$query = new WP_Query( $args );


2. 使用逻辑关系为 AND 的多个条件进行查询。


$args = array(
    'post_type' => 'post',
    'tax_query' => array(
        'relation' => 'AND',
        array(
            'taxonomy' => 'movie_genre',
            'field'    => 'slug',
            'terms'    => array( 'action', 'comedy' ),
        ),
        array(
            'taxonomy' => 'actor',
            'field'    => 'term_id',
            'terms'    => array( 103, 115, 206 ),
            'operator' => 'NOT IN',
        ),
    ),
);
$query = new WP_Query( $args );


2. 使用逻辑关系为 OR 的多个条件进行查询。


$args = array(
    'post_type' => 'post',
    'tax_query' => array(
        'relation' => 'OR',
        array(
            'taxonomy' => 'category',
            'field'    => 'slug',
            'terms'    => array( 'quotes' ),
        ),
        array(
            'taxonomy' => 'post_format',
            'field'    => 'slug',
            'terms'    => array( 'post-format-quote' ),
        ),
    ),
);
$query = new WP_Query( $args );


3. 还可以嵌套使用


$args = array(
    'post_type' => 'post',
    'tax_query' => array(
        'relation' => 'OR',
        array(
            'taxonomy' => 'category',
            'field'    => 'slug',
            'terms'    => array('quotes'),
        ),
        array(
            'relation' => 'AND',
            array(
                'taxonomy' => 'post_format',
                'field'    => 'slug',
                'terms'    => array('post-format-quote'),
            ),
            array(
                'taxonomy' => 'category',
                'field'    => 'slug',
                'terms'    => array('wisdom'),
            ),
        ),
    ),
);
$query = new WP_Query($args);


WP_Query 的基础用法可以参考文章:WP_Query 的基础用法简介

发表评论

暂无评论,抢个沙发...

客服 工单