Does WordPress have a core function that will check if a rest namespace exists?

I would like to use the following function (or something similar) in multiple plugins so it would be helpful if there was something like this available in core.

function rest_namespace_exists( string $namespace ) {
    // Create a rest request for the current rest url of the site
    $request  = \WP_REST_Request::from_url( get_rest_url( null, '' ) );
    $response = rest_do_request( $request );
    $server   = rest_get_server();
    $data     = $server->response_to_data($response, false);

    return array_search( $namespace, $data['namespaces'] ) !== false;

I'm struggling because:

  • If I duplicate the code it's not DRY

  • If I use the above functions in one plugin then I instantly couple the two plugins and have to use both even though I may only want one (depending on each site's requirements).

  • If I build a 'Helper' plugin then I have to ask users who may be using the public plugin to download an additional plugin. Plus I don't know how comfortable I'd feel installing a XYZ Helpers that could have any number of unwanted functions/bloat in it.


You can use the WP_REST_Server::get_namespaces() method.

For instance.

$exists = in_array( 'ns/v1', rest_get_server()->get_namespaces() );
|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.