The WordPress REST API allows applications to interact with your site remotely. However, in certain cases, you might want to disable it to enhance security or limit data access. Here’s how to disable the REST API in WordPress using PHP code:

Steps:

  1. Open the functions.php file of your active theme or create a custom plugin for this adjustment.
  2. Add the following PHP code to disable the REST API for unauthenticated users:
function disable_rest_api( $access ) {
if ( ! is_user_logged_in() ) {
return new WP_Error( 'rest_cannot_access', __( 'REST API has been disabled for unauthenticated users.', 'your-text-domain' ), array( 'status' => 401 ) );
}
return $access;
}
add_filter( 'rest_authentication_errors', 'disable_rest_api' );
  1. Save the changes and verify that unauthenticated users can no longer access the REST API.