Last updated on October 11th, 2023 at 04:34 pm
The permission_callback
parameter in register_rest_route
allows you to define custom permission checks for your WordPress REST API endpoints. I’ve listed down 10 sample use-cases:
1. Open Access
Allowing anyone to access the endpoint, effectively making it public.
'permission_callback' => '__return_true'
2. Authenticated Users Only
Only allowing authenticated users to access the endpoint.
'permission_callback' => function() {
return is_user_logged_in();
}
3. Admin Users Only
Restricting access to users with administrative capabilities.
'permission_callback' => function() {
return current_user_can('manage_options');
}
4. Custom Capability Check
Restricting access based on a custom capability.
'permission_callback' => function() {
return current_user_can('custom_capability');
}
5. Role-based Access
Allowing only users with a specific role to access the endpoint.
'permission_callback' => function() {
$user = wp_get_current_user();
return in_array('editor', $user->roles);
}
6. Rate Limiting
Limiting the number of API calls a user can make within a certain time frame.
'permission_callback' => 'rate_limit_check' // Implement your own rate_limit_check function
7. IP Whitelisting
Allowing only requests from specific IP addresses.
'permission_callback' => function() {
$allowed_ips = ['192.168.0.1', '192.168.0.2'];
return in_array($_SERVER['REMOTE_ADDR'], $allowed_ips);
}
8. Nonce Verification
Validating a nonce passed in either the request header or parameters.
'permission_callback' => function($request) {
$nonce = $request->get_header('X-WP-Nonce');
return wp_verify_nonce($nonce, 'wp_rest');
}
9. OAuth or JWT Authentication
Validating an OAuth token or JWT for external applications.
'permission_callback' => 'validate_oauth_or_jwt_token' // Implement your own function
10. Multiple Conditions
Combining multiple conditions using logical operators.
'permission_callback' => function() {
return is_user_logged_in() && current_user_can('read');
}
Each of these permission_callback
examples serves a different purpose and can be adapted to fit the specific requirements of your plugin or application.
#Vishal #123456