Add code snippet to functions.php of your theme (chid theme preferible)
// WPCODETRICKS.COM - REST API ONLY FOR ADMINS
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 are not currently logged in.', array( 'status' => 401 ) );
}
if ( ! current_user_can( 'administrator' ) ) {
return new WP_Error( 'rest_not_admin', 'You are not an administrator.', array( 'status' => 401 ) );
}
return $result;
});
This code will show a message like next one for not logged users:
{“code”:”rest_not_logged_in”,”message”:”You are not currently logged in.”,”data”:{“status”:401}}
Complete Disable WP REST API
You can completely disable REST API if you will not edit posts or pages (will faill when create or edit, simply disable code when need)
// WPCODETRICKS.COM - COMPLETELY Disable WP REST API
function completely_disable_rest_api( $access ) {
return new WP_Error( 'rest_cannot_access', __( 'Deshabilitada la REST API', 'your-text-domain' ), array( 'status' => rest_authorization_required_code() ) );
}
add_filter( 'rest_authentication_errors', 'completely_disable_rest_api' );