Skip to content

Early-bird lifetime licence: $199 once, for the first 200 buyers only. See the offer

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.

  • Type PHP
  • Runs Everywhere
PHP
// 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.

Move your snippets over this afternoon.

Importing changes nothing until you switch over, and your old shortcodes keep working.