Search code examples
jsonwordpress-rest-api

Is there any way to return a custom error on permission_callback in WordPress REST API


I have registered route with this 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 */;
                }
            ]
        );

I got this message when permission callback function return false:

{
    "code": "rest_forbidden",
    "message": "Sorry, you are not allowed to do that.",
        "data": {
        "status": 401
    }
}

Is there any way to customize this message - hook, filter, etc.? I use a different data format on frontend for successfull responses, so I need to modify these responses too. Thanks in advance for any reply!


Solution

  • It is easy to accomplish:

    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() )
                        );
                    }
                }
            ]
        );