wp api - Core function to check if a rest namespace exists

admin2025-06-06  4

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.

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.

Share Improve this question asked Oct 31, 2018 at 17:37 mrmadhatmrmadhat 9210 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 2

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

For instance.

$exists = in_array( 'ns/v1', rest_get_server()->get_namespaces() );
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1749216687a317340.html

最新回复(0)