The WordPress REST API is a powerful tool that allows interaction with your site through HTTP requests. However, there may be instances where you want to restrict API access, especially for unauthenticated users, for security or privacy reasons.
How to disable REST API access for unauthenticated users?
By default, WordPress allows certain REST API endpoints to be publicly accessible. To restrict this access, you can use the rest_authentication_errors
filter. The following code blocks REST API requests for any unauthenticated user and returns a custom error message.
What does this code do?
- Filter
rest_authentication_errors
: This filter is used to handle authentication errors in the REST API. - Check for pre-existing errors: If
$result
already contains an error, it returns it as is. - User session verification: If the user is not logged in (
!is_user_logged_in()
), it returns aWP_Error
with a custom message and an HTTP 401 (Unauthorized) status code. - Return results: If none of the above conditions are met, it proceeds with normal request handling.
Result
With this code in place, any unauthenticated user will receive an error message stating they must log in to access the REST API. This effectively secures your REST API from unauthorized access.
Leave A Comment