WordPress REST API 请求文章列表接口:
GET /wp/v2/posts
参数 | 说明 |
---|---|
author | 将结果集限制为分配给特定作者的文章。 |
author_exclude | 确保结果集不包含分配给特定作者的文章。 |
要想限制作者只读自己文章,前端只需要仅传送作者ID便可。
axios.get( /wp-json/wp/v2/posts, { params: {
author: 123 // 作者ID
} })
而后端方面,则需要处理一个过滤器rest_post_query
,在系统实际读取文章列表前让我们拓展管理参数:
function custom_limit_rest_post_query( $args, $request ) {
$user_id = get_current_user_id(); // 当前请求用户的ID
$args['author'] = $user_id; // 强制添加author参数
$args['author__in'] = array();
$args['author__not_in'] = array();
return $args;
}
add_filter( 'rest_post_query', 'custom_limit_rest_post_query', 10, 2 );
author__in
和author__not_in
分别对应前端参数author
和author_exclude
,系统在执行该过滤器前,会先将接收的一些参数存到新属性中,类似的还有post__in
和post__not_in
等。
可以看下完整参数$query_args结构:
"query_args": {
"author__in": [100],
"author__not_in": [],
"post__not_in": [],
"post__in": [],
"order": "desc",
"orderby": "date",
"paged": 1,
"post_status": [
"any",
"draft"
],
"date_query": [],
"posts_per_page": 20,
"tax_query": [
{
"taxonomy": "category",
"field": "term_id",
"terms": [
3,
4
],
"include_children": false,
"operator": "IN"
}
],
"post_type": "post",
"author": 200,
"meta_key": null,
"meta_value": null,
"meta_query": null,
"ignore_sticky_posts": true
}
看得出,过滤器中补充的$args['author']
是全新的属性,如果不处理author__in
和author__not_in
,系统会将这些author信息合并,然后再读取文章列表,自然得不到理想结果。其实后端如此处理,基本相当于无视前端传入的author相关参数。
原理基本就是这样,具体参数逻辑可根据需求自定义,比如让管理员不受此限制:
if (!current_user_can('manage_options')) {
$args['author'] = $user_id;
$args['author__in'] = array();
$args['author__not_in'] = array();
}
另外,限制作者只读自己媒体库资源,用同样方法处理过滤器rest_attachment_query
即可。
注意:本文方法不适用于WordPress传统方式登录后台的列表拉取。