Disable REST API for non-logged users in WordPress

Disable REST API without using a plugin.

Add the following code to the functions.php file in your theme or in a custom plugin.

/**
 * Disable REST API for non-logged users.
 *
 * @param $access
 *
 * @return mixed|WP_Error
 */
function zerowp_disable_rest_api($access)
{
    if (is_user_logged_in()) {
        return $access;
    }

    $errorMessage = 'REST API is disabled!';

    if (!is_wp_error($access)) {
        return new WP_Error(
            'rest_api_disabled',
            $errorMessage, [
            'status' => rest_authorization_required_code(),
        ]);
    }

    $access->add(
        'rest_api_disabled',
        $errorMessage, [
        'status' => rest_authorization_required_code(),
    ]);

    return $access;
}

add_filter('rest_authentication_errors', 'zerowp_disable_rest_api', 99);
Member since January 2, 2019

Fullstack Web Developer with more than 12 years of experience in web development. Adept in all stages of advanced web development. Knowledgeable in the user interface, backend, testing, and debugging processes. Bringing forth expertise in design, installation, testing, and maintenance of web systems. Working exclusively and professionally with WordPress since 2010.

Comments

    Your email address will not be published. Required fields are marked *