In WordPress REST API, if a permission callback returns false, what is the expected behavior when a client tries to access that endpoint?
register_rest_route('myplugin/v1', '/data', [ 'methods' => 'GET', 'callback' => 'myplugin_get_data', 'permission_callback' => 'myplugin_check_permission' ]); function myplugin_check_permission() { return false; }
Think about what permission denied means in web APIs.
When a permission callback returns false, WordPress REST API responds with a 403 Forbidden status. This means the client is not allowed to access the endpoint.
Which of the following is the correct way to define a permission callback for a REST API route in WordPress?
register_rest_route('myplugin/v1', '/item', [ 'methods' => 'POST', 'callback' => 'myplugin_create_item', 'permission_callback' => ??? ]);
Remember, permission_callback expects a callable, not the result of a function call.
The permission_callback must be a callable function name or closure. Passing the function name as a string is correct. Calling the function immediately (with parentheses) is wrong.
Consider this permission callback function:
function myplugin_permission() {
return current_user_can('edit_posts') ? true : false;
echo 'Check permission';
}Why does this cause a fatal error?
register_rest_route('myplugin/v1', '/check', [ 'methods' => 'GET', 'callback' => 'myplugin_callback', 'permission_callback' => 'myplugin_permission' ]);
Check the function signature against how WordPress calls permission callbacks (with $request).
WordPress REST API calls permission callbacks with a WP_REST_Request argument. Defining the function without a parameter causes a PHP ArgumentCountError (fatal error) when called.
If a permission callback returns a WP_Error object instead of true or false, what will the REST API response be?
function myplugin_permission() {
return new WP_Error('rest_forbidden', 'You do not have permission', ['status' => 403]);
}
register_rest_route('myplugin/v1', '/error', [
'methods' => 'GET',
'callback' => 'myplugin_callback',
'permission_callback' => 'myplugin_permission'
]);WP_Error objects are used to send error responses in WordPress REST API.
Returning a WP_Error from permission_callback causes the REST API to send the error status and message to the client.
Why is it better to use a permission_callback in WordPress REST API routes rather than checking permissions inside the main callback function?
Think about performance and security when handling API requests.
Using permission callbacks stops unauthorized requests early, avoiding running costly code in the main callback. This improves security and efficiency.