This article describes how to disable access to the WordPress REST API for non-authenticated users.
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.
To disable access to the REST API for non-authenticated users, follow these steps:
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; });
For more information about the REST API in WordPress, please visit https://developer.wordpress.org/rest-api.
Subscribe to receive weekly cutting edge tips, strategies, and news you need to grow your web business.
No charge. Unsubscribe anytime.
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.
We use cookies to personalize the website for you and to analyze the use of our website. You consent to this by clicking on "I consent" or by continuing your use of this website. Further information about cookies can be found in our Privacy Policy.