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

As a seasoned WordPress developer with expertise in various tech stacks and languages, I bring years of experience to every project I undertake. My passion for coding and dedication to delivering exceptional work ensures that every project I undertake is of the highest quality. I specialize in creating custom themes, developing plugins, and building full-scale web systems. By staying up-to-date with the latest industry trends and best practices, I am able to incorporate cutting-edge solutions into my work.

Comments

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