register_rest_route
Registers a REST API route.
Description
register_rest_route( (string) $namespace, (string) $route, (array) $args = array(), (bool) $override = false );
Parameters (4)
- 0. $namespace (string)
- The first URL segment after core prefix. Should be unique to your package/plugin.
- 1. $route (string)
- The base URL for route you are adding.
- 2. $args — Optional. (array) =>
array()
- Either an array of options for the endpoint, or an array of arrays for multiple methods. Default empty array.
- 3. $override — Optional. (bool) =>
false
- If the route already exists, should we override it? True overrides, false merges (with newer overriding if duplicate keys exist). Default false.
Usage
if ( !function_exists( 'register_rest_route' ) ) { require_once ABSPATH . WPINC . '/rest-api.php'; } // The first URL segment after core prefix. Should be unique to your package/plugin. $namespace = ''; // The base URL for route you are adding. $route = ''; // Optional. Either an array of options for the endpoint, or an array of arrays for // multiple methods. Default empty array. $args = array(); // Optional. If the route already exists, should we override it? True overrides, // false merges (with newer overriding if duplicate keys exist). Default false. $override = false; // NOTICE! Understand what this does before running. $result = register_rest_route($namespace, $route, $args, $override);
Defined (1)
The function is defined in the following location(s).
- /wp-includes/rest-api.php
- function register_rest_route( $namespace, $route, $args = array(), $override = false ) {
- /** @var WP_REST_Server $wp_rest_server */
- global $wp_rest_server;
- if ( empty( $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;
- } else if ( empty( $route ) ) {
- _doing_it_wrong( 'register_rest_route', __( 'Route must be specified.' ), '4.4.0' );
- return false;
- }
- 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'] );
- }
- $full_route = '/' . trim( $namespace, '/' ) . '/' . trim( $route, '/' );
- $wp_rest_server->register_route( $namespace, $full_route, $args, $override );
- return true;
- }