Home > AI > Backend > Wordpress > REST >

register_rest_route

register_rest_route( string $namespace, string $route, array $args = array(), bool $override = false )


Parameters 
$namespace
(string) (Required) The first URL segment after core prefix. Should be unique to your package/plugin.

$route
(string) (Required) The base URL for route you are adding.

$args
(array) (Optional) Either an array of options for the endpoint, or an array of arrays for multiple methods.

Default value: array()

$override
(bool) (Optional) If the route already exists, should we override it? True overrides, false merges (with newer overriding if duplicate keys exist).

Default value: false



Return
(bool) True on success, false on error.

Example: create an endpoint that would return the phrase “Hello World, this is the WordPress REST API” when it receives a GET request

/*
 * This is our callback function that embeds our phrase in a WP_REST_Response
 */
function prefix_get_endpoint_phrase() {
    // rest_ensure_response() wraps the data we want to return into a WP_REST_Response, and ensures it will be properly returned.
    return rest_ensure_response( 'Hello World, this is the WordPress REST API' );
}

/**
 * This function is where we register our routes for our example endpoint.
 */
function prefix_register_example_routes() {
    // register_rest_route() handles more arguments but we are going to stick to the basics for now.
    register_rest_route( 'hello-world/v1', '/phrase', array(
        // By using this constant we ensure that when the WP_REST_Server changes our readable endpoints will work as intended.
        'methods'  => WP_REST_Server::READABLE,
        // Here we register our callback. The callback is fired when this endpoint is matched by the WP_REST_Server class.
        'callback' => 'prefix_get_endpoint_phrase',
    ) );
}

add_action( 'rest_api_init', 'prefix_register_example_routes' );

Then you can access https://ourawesomesite.com/wp-json/hello-world/v1/phrase to have a look.

The first argument passed into register_rest_route() is the namespace, which provides us a way to group our routes.

The second argument passed in is the resource path, or resource base. For our example, the resource we are retrieving is the “Hello World, this is the WordPress REST API” phrase.

The third argument is an array of options. We specify what methods the endpoint can use and what callback should happen when the endpoint is matched (more things can be done but these are the fundamentals).

The third argument also allows us to provide a permissions callback, which can restrict access for the endpoint to only certain users. The third argument also offers a way to register arguments for the endpoint so that requests can modify the response of our endpoint.

Leave a Reply