WP_REST_Server::register_route PHP Method

register_route() public method

Registers a route to the server.
Since: 4.4.0
public register_route ( string $namespace, string $route, array $route_args, boolean $override = false )
$namespace string Namespace.
$route string The REST route.
$route_args array Route arguments.
$override boolean Optional. Whether the route should be overridden if it already exists. Default false.
    public function register_route($namespace, $route, $route_args, $override = false)
    {
        if (!isset($this->namespaces[$namespace])) {
            $this->namespaces[$namespace] = array();
            $this->register_route($namespace, '/' . $namespace, array(array('methods' => self::READABLE, 'callback' => array($this, 'get_namespace_index'), 'args' => array('namespace' => array('default' => $namespace), 'context' => array('default' => 'view')))));
        }
        // Associative to avoid double-registration.
        $this->namespaces[$namespace][$route] = true;
        $route_args['namespace'] = $namespace;
        if ($override || empty($this->endpoints[$route])) {
            $this->endpoints[$route] = $route_args;
        } else {
            $this->endpoints[$route] = array_merge($this->endpoints[$route], $route_args);
        }
    }

Usage Example

 public function test_get_namespaces()
 {
     $server = new WP_REST_Server();
     $server->register_route('test/example', '/test/example/some-route', array(array('methods' => WP_REST_Server::READABLE, 'callback' => '__return_true')));
     $server->register_route('test/another', '/test/another/route', array(array('methods' => WP_REST_Server::READABLE, 'callback' => '__return_false')));
     $namespaces = $server->get_namespaces();
     $this->assertContains('test/example', $namespaces);
     $this->assertContains('test/another', $namespaces);
 }
All Usage Examples Of WP_REST_Server::register_route