How to remove users from WP-JSON

Increase your site's security by hiding usernames from WP-JSON, that are otherwise exposed to the public.

Not everyone knows this, but by default WordPress exposes 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;
});

Leave a Reply

Your email address will not be published.