Disable WordPress REST API

This code snippet disables the WordPress REST API by using the ‘rest_authentication_errors’ filter.

The WordPress REST API provides endpoints for WordPress data types that allow developers to interact with sites remotely by sending and receiving JSON (JavaScript Object Notation) objects. While it offers a lot of possibilities, it’s not always needed and some site owners choose to disable it for security or performance reasons.

The code defines a callback function for the ‘rest_authentication_errors’ filter which returns a new WP_Error object. The WP_Error is constructed with an error code of ‘rest_disabled’, a message stating that the REST API has been disabled, and an array specifying a ‘status’ code which is retrieved by the rest_authorization_required_code() function. This effectively makes the REST API return an error whenever it is accessed.

This filter should be added to the functions.php file in your theme, or a site-specific plugin. Please keep in mind that if you have plugins that rely on the REST API, they may stop working after implementing this code. Always test changes on a staging site before applying them to a live website.

PHP
add_filter(
	'rest_authentication_errors',
	function ( $access ) {
		return new WP_Error(
			'rest_disabled',
			__( 'The WordPress REST API has been disabled.' ),
			array(
				'status' => rest_authorization_required_code(),
			)
		);
	}
);