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.

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 log in to access the REST API.’, array(‘status’ => 401));
}
return $result;
});

What does this code do?

  1. Filter rest_authentication_errors: This filter is used to handle authentication errors in the REST API.
  2. Check for pre-existing errors: If $result already contains an error, it returns it as is.
  3. User session verification: If the user is not logged in (!is_user_logged_in()), it returns a WP_Error with a custom message and an HTTP 401 (Unauthorized) status code.
  4. 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.