WordPress REST API限制作者(author)只读自己文章的方法

WordPress REST API 请求文章列表接口:

GET  /wp/v2/posts
参数说明
author将结果集限制为分配给特定作者的文章。
author_exclude确保结果集不包含分配给特定作者的文章。

要想限制作者只读自己文章,前端只需要仅传送作者ID便可。

axios.get( /wp-json/wp/v2/posts, { params: {
	author: 123       // 作者ID
} })

WordPress REST API
而后端方面,则需要处理一个过滤器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__inauthor__not_in分别对应前端参数authorauthor_exclude,系统在执行该过滤器前,会先将接收的一些参数存到新属性中,类似的还有post__inpost__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__inauthor__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传统方式登录后台的列表拉取。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值