How to disable REST API endpoints in WordPress

This article describes how to disable access to the WordPress REST API for non-authenticated users.

What is the REST API?

The REST API provides a way for applications to interact with a WordPress site. By using special URLs, applications can send and receive data using the popular JSON (JavaScript Object Notation) format.

By default, WordPress provides several REST URI endpoints to site resources. However, these REST endpoints are accessible by non-authenticated users. For example, the users endpoint provides information about a site's users. For security reasons, you may not want this information to be accessible to everyone.

Disabling the REST API completely, however, breaks WordPress administrative functionality. If you want to disable access to REST API endpoints, you should instead only accept requests from authenticated users.

Disabling the REST API for non-authenticated users

To disable access to the REST API for non-authenticated users, follow these steps:

  1. Log in to WordPress as the administrator.
  2. On the Dashboard in the left sidebar, click Appearance, and then click Theme Editor:

    WordPress - Dashboard - Appearance - Theme Editor

  3. In the right sidebar, under Theme Files, click Theme Functions (functions.php).
  4. Copy the following code snippet and then paste it at the bottom of the functions.php file:

    add_filter( 'rest_authentication_errors', function( $result ) {
        if ( true === $result || is_wp_error( $result ) ) {
            return $result;
        }
    
        if ( ! is_user_logged_in() ) {
            return new WP_Error(
                'rest_not_logged_in',
                __( 'You are not currently logged in.' ),
                array( 'status' => 401 )
            );
        }
    
        return $result;
    });
    
  5. Click Update File. WordPress saves the changes to the functions.php file.
  6. The REST API is now disabled for non-authenticated users. To test this, use your web browser to go to https://example.com/wp-json/wp/v2, where example.com represents your domain name. If you are not logged in, you receive the “You are not currently logged in” message. If you are logged in, a large set of JSON output appears.

More Information

For more information about the REST API in WordPress, please visit https://developer.wordpress.org/rest-api.

Get WordPress Hosting

Article Details

Other Articles in This Category

Show More

Did you find this article helpful? Then you'll love our support. Experience the A2 Hosting difference today and get a pre-secured, pre-optimized website. Check out our web hosting plans today.

 

 

Loading