有什么方法可以 return 在 WordPress REST API 中 permission_callback 上的自定义错误
Is there any way to return a custom error on permission_callback in WordPress REST API
我已经用这个代码注册了路线
register_rest_route(
"v1/senders",
"read",
[
"methods" => WP_REST_Server::READABLE,
"callback" => [
new Sender(),
"read"
],
"permission_callback" => function ( WP_REST_Request $request ) {
return /* Function returning true/false */;
}
]
);
我在权限回调函数 return 时收到此消息 false:
{
"code": "rest_forbidden",
"message": "Sorry, you are not allowed to do that.",
"data": {
"status": 401
}
}
有没有办法自定义此消息 - 挂钩、过滤器等?我在前端使用不同的数据格式来获得成功的响应,所以我也需要修改这些响应。提前感谢您的回复!
很容易做到:
register_rest_route(
"v1/senders",
"read",
[
"methods" => WP_REST_Server::READABLE,
"callback" => [
new Sender(),
"read"
],
"permission_callback" => function ( $request ) {
//Function returning true/false/WP_Error;
if( YES ){ //-->your custom permission condition!
return true;
}else{
//Modify the below message and/or status code if you want!
return new WP_Error(
'rest_forbidden',
__( 'Sorry, you are not allowed to do that!!!.' ),
array( 'status' => rest_authorization_required_code() )
);
}
}
]
);
"permission_callback" => function ( $request ) {
return new \WP_Error(
'rest_cannot_view',
__( 'Sorry, you cannot list resources.' ),
array( 'status' => rest_authorization_required_code() ));
}
我已经用这个代码注册了路线
register_rest_route(
"v1/senders",
"read",
[
"methods" => WP_REST_Server::READABLE,
"callback" => [
new Sender(),
"read"
],
"permission_callback" => function ( WP_REST_Request $request ) {
return /* Function returning true/false */;
}
]
);
我在权限回调函数 return 时收到此消息 false:
{
"code": "rest_forbidden",
"message": "Sorry, you are not allowed to do that.",
"data": {
"status": 401
}
}
有没有办法自定义此消息 - 挂钩、过滤器等?我在前端使用不同的数据格式来获得成功的响应,所以我也需要修改这些响应。提前感谢您的回复!
很容易做到:
register_rest_route(
"v1/senders",
"read",
[
"methods" => WP_REST_Server::READABLE,
"callback" => [
new Sender(),
"read"
],
"permission_callback" => function ( $request ) {
//Function returning true/false/WP_Error;
if( YES ){ //-->your custom permission condition!
return true;
}else{
//Modify the below message and/or status code if you want!
return new WP_Error(
'rest_forbidden',
__( 'Sorry, you are not allowed to do that!!!.' ),
array( 'status' => rest_authorization_required_code() )
);
}
}
]
);
"permission_callback" => function ( $request ) { return new \WP_Error( 'rest_cannot_view', __( 'Sorry, you cannot list resources.' ), array( 'status' => rest_authorization_required_code() )); }