Hide the REST Users Endpoint From Subscribers and Customers
Blocks the REST API users endpoint for logged-in users who cannot edit posts, such as subscribers and shop customers, so a low-level account cannot list your authors and their usernames.
Opens WPIDE on
Code
add_filter( 'rest_pre_dispatch', function ( $result, $server, $request ) {
$route = $request->get_route();
if ( null !== $result || 0 !== strpos( $route, '/wp/v2/users' ) || ! is_user_logged_in() || current_user_can( 'edit_posts' ) ) {
return $result;
}
if ( '/wp/v2/users/me' === untrailingslashit( $route ) ) {
return $result;
}
return new WP_Error( 'rest_user_cannot_view', 'Sorry, you are not allowed to list users.', array( 'status' => 403 ) );
}, 10, 3 );
Notes
Authors, editors and administrators keep access because the block editor needs it; their own /users/me request keeps working for everyone.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.