Skip to main content
Login Join
Snippet · PHP

Disable WordPress REST API for Non-Logged-In Users

Shared by Amit Dholiya · May 25, 2026

9 views
Back to Snippets

If your site doesn’t use the REST API publicly, you can restrict access to logged-in users only.

Steps

  1. Open your WordPress theme functions.php file.
  2. Add the code below at the end of the file.
  3. Save the file.
  4. Test by visiting: yoursite.com/wp-json/

Done — only logged-in users will be able to access the REST API.

add_filter('rest_authentication_errors', function ($result) {
    if (!empty($result)) {
        return $result;
    }

    if (!is_user_logged_in()) {
        return new WP_Error(
            'rest_not_logged_in',
            'You must be logged in to access the REST API.',
            array('status' => 401)
        );
    }

    return $result;
});
Know a different way to do this? Add your approach as a variation so folks can compare them side by side.
Submit a variation

0 comments