Disable the REST API users endpoints for visitors
Hide /wp-json/wp/v2/users from logged-out visitors so your WordPress usernames aren't public. The block editor keeps working.
// Hide the REST API users endpoints from visitors who are not logged in.
add_filter(
'rest_endpoints',
function ( $endpoints ) {
if ( is_user_logged_in() ) {
return $endpoints;
}
foreach ( array_keys( $endpoints ) as $route ) {
if ( 0 === strpos( $route, '/wp/v2/users' ) ) {
unset( $endpoints[ $route ] );
}
}
return $endpoints;
}
);
What it does
By default anyone can open /wp-json/wp/v2/users and see the name and URL slug of everyone who has published a post. The slug is often the login name.
This snippet removes the /wp/v2/users routes for visitors who aren't logged in. Logged-in users, including everyone using the block editor, see no change. The rest of the REST API keeps working.
Good to know
- Plugins or apps that read the users list without logging in will get a "No route was found" error.
- Use it together with the "Block user enumeration via ?author=" snippet.