自定义分类法

有关自定义分类法(Taxonomy)的查询可以使用 1 个参数:

tax_query(数组):分类法查询参数
relation(字符串):条件的逻辑关系,OR(或者)或 AND(和)
taxonomy(字符串):分类法名称
field(字符串):根据分类法条款的什么字段查询,可选 term_id(分类条款 ID)、name(名称)和 slug(别名),默认是 term_id
terms(整数 | 字符串 | 分类):分类法条款
include_children(布尔):是否包含子分类法条款,默认是 True
operator(字符串):匹配运算符(IN、IN NOT 和 AND),默认是 IN

简单的分类法查询
获取 people 分类法里别名为 bob 的条款下的文章:


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

多分类法查询
获取同时是 movie_genre 分类法下别名为 action 或 comedy 的条款的文章和不是 actor 分类法下 ID 为 103 或 115 或 206 的条款的文章(略拗口):


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

获取是分类法 category(也就是分类)下别名为 quotes 的条款或是分类法 post_format 下别名为 post-format-quote 的条款的文章:


$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 );