注册REST API路由。

原型

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

参数

$namespace (string) (Required) 核心前缀后的第一个URL段。应该是你的包/插件的独特之处。

$route (string) (Required) 要添加的路由的基本URL。

$args (array) (Optional)  端点的选项数组或多个方法的数组数组。

$override (bool) (Optional)  如果路线已经存在,我们应该覆盖它吗?真正的覆盖,错误的合并(如果存在重复的密钥则使用更新的覆盖)。

返回值

(bool)  成功时为真,错误时为假。

源文件

路径:wp-includes/rest-api.php

<?php
...
function register_rest_route( $namespace, $route, $args = array(), $override = false ) {
	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, '/' );
	rest_get_server()->register_route( $namespace, $full_route, $args, $override );
	return true;
}
...
?>

其他

英文文档:https://developer.wordpress.org/reference/functions/register_rest_route/