If your site doesn’t use the REST API publicly, you can restrict access to logged-in users only.
Steps
- Open your WordPress theme
functions.phpfile. - Add the code below at the end of the file.
- Save the file.
- Test by visiting: yoursite.com/wp-json/
Done — only logged-in users will be able to access the REST API.
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 be logged in to access the REST API.',
array('status' => 401)
);
}
return $result;
});