Build Safer WordPress Sites: Disable REST API Access for Guests

Learn how to disable the REST API in your WordPress site for logged-out users.

Meet WPCodeBox: The Best Code Snippets Plugin for WordPress
faces
Join thousands of developers and agencies who are working better and faster using WPCodeBox

By default, the WordPress REST API exposes data publicly, even to logged-out users. This can be a security concern if you want to protect sensitive information.

To fix this, you can disable REST API access for guests using a simple snippet. Logged-out users will be blocked, while logged-in users will still have full access to the API.

Below is the code snippet from the video used to disable the REST API:

function disable_rest_api_for_guests($access) {
    if(!is_user_logged_in()) {
        return new WP_Error(
            'rest_disabled',
            __('The REST API is disabled for guests.'),
            array('status' => 403)
        );
    }

    return $access;
}

add_filter('rest_authentication_errors','disable_rest_api_for_guests');

Related Tutorials

WPCodeBox is a WordPress Code Snippets Manager that allows you to share your WordPress Code Snippets across your sites.