Registers a REST API route.
Description
Note: Do not use before the ‘rest_api_init’ hook.
Parameters
$route_namespace
stringrequired- The first URL segment after core prefix. Should be unique to your package/plugin.
$route
stringrequired- The base URL for route you are adding.
$args
arrayoptional- Either an array of options for the endpoint, or an array of arrays for multiple methods.
Default:
array()
$override
booloptional- If the route already exists, should we override it? True overrides, false merges (with newer overriding if duplicate keys exist).
Default:
false
Source
function register_rest_route( $route_namespace, $route, $args = array(), $override = false ) {
if ( empty( $route_namespace ) ) {
/*
* Non-namespaced routes are not allowed, with the exception of the main
* and namespace indexes. If you really need to register a
* non-namespaced route, call `WP_REST_Server::register_route` directly.
*/
_doing_it_wrong( 'register_rest_route', __( 'Routes must be namespaced with plugin or theme name and version.' ), '4.4.0' );
return false;
} elseif ( empty( $route ) ) {
_doing_it_wrong( 'register_rest_route', __( 'Route must be specified.' ), '4.4.0' );
return false;
}
$clean_namespace = trim( $route_namespace, '/' );
if ( $clean_namespace !== $route_namespace ) {
_doing_it_wrong( __FUNCTION__, __( 'Namespace must not start or end with a slash.' ), '5.4.2' );
}
if ( ! did_action( 'rest_api_init' ) ) {
_doing_it_wrong(
'register_rest_route',
sprintf(
/* translators: %s: rest_api_init */
__( 'REST API routes must be registered on the %s action.' ),
'<code>rest_api_init</code>'
),
'5.1.0'
);
}
if ( isset( $args['args'] ) ) {
$common_args = $args['args'];
unset( $args['args'] );
} else {
$common_args = array();
}
if ( isset( $args['callback'] ) ) {
// Upgrade a single set to multiple.
$args = array( $args );
}
$defaults = array(
'methods' => 'GET',
'callback' => null,
'args' => array(),
);
foreach ( $args as $key => &$arg_group ) {
if ( ! is_numeric( $key ) ) {
// Route option, skip here.
continue;
}
$arg_group = array_merge( $defaults, $arg_group );
$arg_group['args'] = array_merge( $common_args, $arg_group['args'] );
if ( ! isset( $arg_group['permission_callback'] ) ) {
_doing_it_wrong(
__FUNCTION__,
sprintf(
/* translators: 1: The REST API route being registered, 2: The argument name, 3: The suggested function name. */
__( 'The REST API route definition for %1$s is missing the required %2$s argument. For REST API routes that are intended to be public, use %3$s as the permission callback.' ),
'<code>' . $clean_namespace . '/' . trim( $route, '/' ) . '</code>',
'<code>permission_callback</code>',
'<code>__return_true</code>'
),
'5.5.0'
);
}
foreach ( $arg_group['args'] as $arg ) {
if ( ! is_array( $arg ) ) {
_doing_it_wrong(
__FUNCTION__,
sprintf(
/* translators: 1: $args, 2: The REST API route being registered. */
__( 'REST API %1$s should be an array of arrays. Non-array value detected for %2$s.' ),
'<code>$args</code>',
'<code>' . $clean_namespace . '/' . trim( $route, '/' ) . '</code>'
),
'6.1.0'
);
break; // Leave the foreach loop once a non-array argument was found.
}
}
}
$full_route = '/' . $clean_namespace . '/' . trim( $route, '/' );
rest_get_server()->register_route( $clean_namespace, $full_route, $args, $override );
return true;
}
Since WP 5.5.0 there is a notice if your registration of REST API route is not including the `
permission_callback
`. You may get some notice in debug.log like the following one:PHP Notice: register_rest_route was called incorrectly. The REST API route definition for
/foo
is missing the requiredpermission_callback
argument. For REST API routes that are intended to be public, use__return_true
as the permission callback.To solve this problem you will need to add the `
permission_callback
` in arguments like the example from the “Routes and Endpoints Handbook”: https://developer.wordpress.org/rest-api/extending-the-rest-api/routes-and-endpoints/#permissions-callbackArgs is a named array that usually includes the keys ‘methods’ and ‘callback’.
‘method’ defines which HTTP methods are to be processed by the function defined by ‘callback’.
‘method’ can be a string of comma-separated HTTP methods or an array of strings of HTTP methods.
A common practice is to use the WP_REST_Server constants to set the ‘method’.
WP_REST_Server::READABLE = ‘GET’
WP_REST_Server::EDITABLE = ‘POST, PUT, PATCH’
WP_REST_Server::DELETABLE = ‘DELETE’
WP_REST_Server::ALLMETHODS = ‘GET, POST, PUT, PATCH, DELETE’
Example
// Get a list of locations.
// Method GET via wp-json/store-locator-plus//locations/
//
// Calls the get_locations method of the current class when the route is matched.
//
register_rest_route( 'my-plugin-slug/v2' , '/locations/', array(
'methods' => 'GET',
'callback' => array(
$this,
'get_locations'
)
) );
WP_REST_Server::CREATABLE
= ‘POST’Make sure that your regex expressions are fine. If the data does not match then the URL will return a 404.
Some examples are:
(?P[a-zA-Z0-9-]+) for slug (you can change slug for your custom name)
(?P\d+) for id
(?P[a-z0-9 .\-]+) for longitude or latitude
Edited to remove an extra
)
in one of the regexes. – DevHub TeamNote: – licences and /removed only use for example.
In case you are a friend of type hinting and are wondering what is being passed to your
callback
method, it’s aWP_REST_Request
object. It might help you with autocompletion and discovering other methods provided.Args , the named array cited above, can also contain an optional ‘args’ array of its own.
The second args array contains the default arguments, required arguments, validation callback, and sanitization callback that are in place for each argument passed in with the REST request. The key name of this array is the name of the parameter being passed.
See http://v2.wp-api.org/extending/adding/ under the “Arguments” section for more information and examples.
Example
<?php
add_action( 'rest_api_init', function () {
register_rest_route( 'myplugin/v1', '/author/(?P\d+)', array(
'methods' => 'GET',
'callback' => 'my_awesome_func',
'args' => array(
'id' => array(
'validate_callback' => function($param, $request, $key) {
return is_numeric( $param );
}
),
),
) );
} );
1. You can not use
/
(slash) at the beginning or end of the namespace, for example:plugin_name/api/
.2.
permission_callback
is required argument ofregister_rest_route
.1. Callback takes the request object as a parameter.
2. You can set the response headers with
WP_Error
class.permission_callback
is equivalent to granting access. Using'__return_true'
is preferred if the intention is to make an API public.for the non-namespaced routing, call
WP_REST_Server::register_route
directly.Example
will register
foo
endpoint without namespace. You can accesshttp://example.com/wp-json/foo
As a reminder, please ensure before registering non-namespaced routes. They can be useful for backward compatibility only.
The
permission_callback
should return one offalse
,null
, or aWP_Error
if access is to be disallowed. Anything else, including other “falsey” values, will grant access.