Last updated on September 13, 2023

Disable REST API

Don’t know where to add this snippet? Read our guide: How to add code snippets.

Disable the REST API.

WordPress REST API is a powerful feature that allows developers to interact with WordPress using a standard API interface. However, in some cases, you may want to disable the REST API in WordPress to improve security or performance of your site. Here’s an example code snippet to disable the REST API in WordPress:

function wpsnippets_disable_rest_api() {
    add_filter( 'rest_authentication_errors', 'wpsnippets_disable_rest_api_filter' );
}

function wpsnippets_disable_rest_api_filter( $access ) {
    return new WP_Error( 'rest_disabled', __( 'The REST API has been disabled.' ), array( 'status' => 403 ) );
}

add_action( 'rest_api_init', 'wpsnippets_disable_rest_api', 99 );

In this code snippet, we define a function wpsnippets_disable_rest_api that uses the add_filter function to add a filter to the rest_authentication_errors hook. This filter is called when a REST API request is made and checks if the REST API is disabled. We also define a function wpsnippets_disable_rest_api_filter that returns an error if the REST API is disabled. This error message is returned to the user instead of the requested data. Finally, we use the add_action function to add the wpsnippets_disable_rest_api function to the rest_api_init hook. This ensures that the REST API is disabled when the REST API is initialized.

With this code in place, any requests made to the WordPress REST API will return an error message stating that the REST API has been disabled. You can modify the error message to provide more information as needed.

If you want to learn more about the REST API in WordPress, make sure to check out the REST API Handbook!

Last updated on September 13, 2023. Originally posted on May 10, 2023.

Leave a Reply

Your email address will not be published. Required fields are marked *