When you go to /wp-json
or /wp-json/[namespace]
on an API-enabled WordPress site, it shows all of the API routes and endpoints.
How can I disable this behaviour without disabling the REST API?
When you go to /wp-json
or /wp-json/[namespace]
on an API-enabled WordPress site, it shows all of the API routes and endpoints.
How can I disable this behaviour without disabling the REST API?
Slightly modified function from @mirado (the filter has to return WP_REST_Response instance not an array)
function hide_ns_and_routes( $response ) {
$data = $response->get_data();
$data['namespaces'] = [];
$data['routes'] = [];
$response->set_data( $data );
return $response;
}
add_filter( 'rest_index', 'hide_ns_and_routes' );
You can use the filter hook 'rest_index' :
add_filter('rest_index', function ($response) {
$data = $response->get_data();
$data['namespaces'] = [];
$data['routes'] = [];
return $data;
}, 9999, 1);
It is possible to remove your route from $data['namespaces'] and $data['routes']
The previous answers can hide the index display for /wp-json
, but it doesn't seem to work for /wp-json/[namespace]
.
In order to hide the index of a particular namespace, the rest_namespace_index
hook needs to be used.
add_filter('rest_namespace_index', function ($response) {
$data = $response->get_data();
$data['namespaces'] = [];
$data['routes'] = [];
$response->set_data($data);
return $response;
});
If someone wants to completely rewrite the routing output, or wants more flexible permissions control, a better approach would be to re-register the root routing path for that namespace
Unfortunately, register_rest_route
is of little use at this point, as it will reject empty routing paths. Therefore, the rewrite needs to be done directly using the underlying WP_REST_Server::register_route
.
rest_get_server()->register_route($namespace, "/$namespace", [
'methods' => 'GET',
'permission_callback' => fn () => current_user_can('import'),
'callback' => fn ($r) => $this->representationBrowser($r),
], true);
Note that:
route
parameter should be /[namespace]
, not /
.override
parameter may need to be true