在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 的基础用法简介
-
WordPress函数:wp_trash_post_comments 移动文章评论到垃圾站WordPress函数:wp_trash_post_comments 移动文章评论到垃圾站
-
WordPress函数:wp_delete_attachment 删除附件WordPress函数:wp_delete_attachment 删除评论
-
WordPress函数:wp_update_user 更新用户信息WordPress函数:wp_update_user 更新用户信息
-
WordPress函数:add_shortcode 添加短代码WordPress函数:add_shortcode 添加短代码
-
WordPress函数:remove_shortcode 删除短代码WordPress函数:remove_shortcode 删除短代码
-
WordPress函数:current_user_can_for_blog 多站点下检查用户权限WordPress函数:current_user_can_for_blog 多站点下检查用户权限
暂无评论,抢个沙发...