Remove exposed users from WP-JSON

Laptop computer with code displayed on the screen

By default WordPress exposes admin usernames and makes them available for the public to see over WP’s REST API.

A list all of all is available at users https://example.com/wp-json/wp/v2/users and one can also get information about a specific user at https://example.com/wp-json/wp/v2/users/1, where 1 is a user’s ID.

To disable these two endpoints, add this code snippet to your theme’s functions.php file:

// Disable users rest routes
add_filter('rest_endpoints', function( $endpoints ) {
    if ( isset( $endpoints['/wp/v2/users'] ) ) {
        unset( $endpoints['/wp/v2/users'] );
    }
    if ( isset( $endpoints['/wp/v2/users/(?P<id>[\d]+)'] ) ) {
        unset( $endpoints['/wp/v2/users/(?P<id>[\d]+)'] );
    }
    return $endpoints;
});