How to Disable WP REST API in WordPress

Posted by Lasantha Bandara File Under : wordpress

How to Disable WP REST API in WordPress

With WordPress 4.4, a new feature called "WP REST API (WP API / WordPress REST API / WordPress JSON API / WordPress JSON REST API)" was introduced. WordPress REST API makes it possible to access your WordPress website's data through an easy-to-use HTTP REST API, which is awesome for external services and clients.

However, the WP REST API permits external applications and users to retrieve site data via endpoints such as /wp-json/s, potentially leading to security or privacy issues if not necessary.

If you want to reduce exposure to your site's data, improve privacy, and clean up unnecessary links in HTML and HTTP headers, you can disable the WordPress REST API by simply adding the following code to your theme's functions.php file:

// Disable REST API for non-logged-in users
add_filter('rest_authentication_errors', function($result) {
    if (!is_user_logged_in()) {
        return new WP_Error(
            'rest_disabled',
            'The REST API is disabled for non-authenticated users.',
            ['status' => 403]
        );
    }
    return $result;
});

// Remove REST API links from <head> and headers for non-logged-in users
if (!is_user_logged_in()) {
    remove_action('wp_head', 'rest_output_link_wp_head', 10);
    remove_action('template_redirect', 'rest_output_link_header', 11);
}

What the above code does:

  • Returns a 403 Forbidden error for non-logged-in users trying to access REST API endpoints.
  • Removes REST API links from the <head> and response headers for visitors who aren’t logged in.
  • Keeps everything working for logged-in users, including admins, editors, and plugins.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.