Bazujące na WordPress narzędzie wyszukiwania dla deweloperów i twórców motywów.



register_rest_route ›

Od4.4.0
Przestarzałyn/a
register_rest_route ( $namespace, $route, $args = array(), $override = false )
Parametry: (4)
  • (string) $namespace The first URL segment after core prefix. Should be unique to your package/plugin.
    Wymagane: Tak
  • (string) $route The base URL for route you are adding.
    Wymagane: Tak
  • (array) $args Optional. Either an array of options for the endpoint, or an array of arrays for multiple methods. Default empty array.
    Wymagane: Nie
    Domyślny: array()
  • (bool) $override Optional. If the route already exists, should we override it? True overrides, false merges (with newer overriding if duplicate keys exist). Default false.
    Wymagane: Nie
    Domyślny: false
Powrót:
  • (bool) True on success, false on error.
Zdefiniowane na:
Codex:
Dziennik zmian:
  • 5.1.0

Registers a REST API route.

Note: Do not use before the {@see 'rest_api_init'} hook.



Źródło

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;
	} elseif ( empty( $route ) ) {
		_doing_it_wrong( 'register_rest_route', __( 'Route must be specified.' ), '4.4.0' );
		return false;
	}

	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'] );
	}

	$full_route = '/' . trim( $namespace, '/' ) . '/' . trim( $route, '/' );
	rest_get_server()->register_route( $namespace, $full_route, $args, $override );
	return true;
}