This free source code snippet is very simple and uses the WordPress rest_authentication_errors
filter to completely disable the WordPress REST API. What happens here is simply that any request to the REST API, will be responded with a rest_disabled
error.
WordPress enables a public REST API as one of the many features offered out-of-the-box. If you are just discovering WordPress, make sure to have a read here. Also, the WordPress REST API is an interface that developers can use to access WordPress from outside the WordPress installation itself.
You can now open your active theme’s functions.php
and add the following source code:
<?php
add_filter(
'rest_authentication_errors',
function ( $access ) {
return new WP_Error(
'rest_disabled',
__( 'The WordPress REST API has been disabled.' ),
[
'status' => rest_authorization_required_code(),
]
);
}
);
This is a very simple source code, isn’t it? It forces any requests to the REST API such that the endpoints always respond with an array of errors. Thus, it makes sure that your WordPress REST API will never give a response to any request.
You can disable the WordPress REST API and it is common practice in the WordPress community to do so if you are not actively using it. This is because there are a lot of bots which use these API endpoints to post SPAM or to bruteforce your authentication system.
Additionally, there are scenarios where restricting access to a REST API might be a legitimate requirement, such as controlling access to specific endpoints or enforcing authentication mechanisms. Please, always prioritize security and ensure that your implementation complies with relevant regulations and ethical standards.