11 * Version number for our API.
15 define( 'REST_API_VERSION', '2.0' );
18 * Registers a REST API route.
22 * @global WP_REST_Server $wp_rest_server ResponseHandler instance (usually WP_REST_Server).
24 * @param string $namespace The first URL segment after core prefix. Should be unique to your package/plugin.
25 * @param string $route The base URL for route you are adding.
26 * @param array $args Optional. Either an array of options for the endpoint, or an array of arrays for
27 * multiple methods. Default empty array.
28 * @param bool $override Optional. If the route already exists, should we override it? True overrides,
29 * false merges (with newer overriding if duplicate keys exist). Default false.
30 * @return bool True on success, false on error.
32 function register_rest_route( $namespace, $route, $args = array(), $override = false ) {
33 /** @var WP_REST_Server $wp_rest_server */
34 global $wp_rest_server;
36 if ( empty( $namespace ) ) {
38 * Non-namespaced routes are not allowed, with the exception of the main
39 * and namespace indexes. If you really need to register a
40 * non-namespaced route, call `WP_REST_Server::register_route` directly.
42 _doing_it_wrong( 'register_rest_route', __( 'Routes must be namespaced with plugin or theme name and version.' ), '4.4.0' );
44 } else if ( empty( $route ) ) {
45 _doing_it_wrong( 'register_rest_route', __( 'Route must be specified.' ), '4.4.0' );
49 if ( isset( $args['callback'] ) ) {
50 // Upgrade a single set to multiple.
51 $args = array( $args );
59 foreach ( $args as $key => &$arg_group ) {
60 if ( ! is_numeric( $arg_group ) ) {
61 // Route option, skip here.
65 $arg_group = array_merge( $defaults, $arg_group );
68 $full_route = '/' . trim( $namespace, '/' ) . '/' . trim( $route, '/' );
69 $wp_rest_server->register_route( $namespace, $full_route, $args, $override );
74 * Registers rewrite rules for the API.
78 * @see rest_api_register_rewrites()
79 * @global WP $wp Current WordPress environment instance.
81 function rest_api_init() {
82 rest_api_register_rewrites();
85 $wp->add_query_var( 'rest_route' );
89 * Adds REST rewrite rules.
93 * @see add_rewrite_rule()
95 function rest_api_register_rewrites() {
96 add_rewrite_rule( '^' . rest_get_url_prefix() . '/?$','index.php?rest_route=/','top' );
97 add_rewrite_rule( '^' . rest_get_url_prefix() . '/(.*)?','index.php?rest_route=/$matches[1]','top' );
101 * Registers the default REST API filters.
103 * Attached to the {@see 'rest_api_init'} action
104 * to make testing and disabling these filters easier.
108 function rest_api_default_filters() {
109 // Deprecated reporting.
110 add_action( 'deprecated_function_run', 'rest_handle_deprecated_function', 10, 3 );
111 add_filter( 'deprecated_function_trigger_error', '__return_false' );
112 add_action( 'deprecated_argument_run', 'rest_handle_deprecated_argument', 10, 3 );
113 add_filter( 'deprecated_argument_trigger_error', '__return_false' );
116 add_filter( 'rest_pre_serve_request', 'rest_send_cors_headers' );
117 add_filter( 'rest_post_dispatch', 'rest_send_allow_header', 10, 3 );
119 add_filter( 'rest_pre_dispatch', 'rest_handle_options_request', 10, 3 );
123 * Loads the REST API.
127 * @global WP $wp Current WordPress environment instance.
128 * @global WP_REST_Server $wp_rest_server ResponseHandler instance (usually WP_REST_Server).
130 function rest_api_loaded() {
131 if ( empty( $GLOBALS['wp']->query_vars['rest_route'] ) ) {
136 * Whether this is a REST Request.
141 define( 'REST_REQUEST', true );
143 // Initialize the server.
144 $server = rest_get_server();
146 // Fire off the request.
147 $server->serve_request( $GLOBALS['wp']->query_vars['rest_route'] );
154 * Retrieves the URL prefix for any API resource.
158 * @return string Prefix.
160 function rest_get_url_prefix() {
162 * Filter the REST URL prefix.
166 * @param string $prefix URL prefix. Default 'wp-json'.
168 return apply_filters( 'rest_url_prefix', 'wp-json' );
172 * Retrieves the URL to a REST endpoint on a site.
174 * Note: The returned URL is NOT escaped.
178 * @todo Check if this is even necessary
180 * @param int $blog_id Optional. Blog ID. Default of null returns URL for current blog.
181 * @param string $path Optional. REST route. Default '/'.
182 * @param string $scheme Optional. Sanitization scheme. Default 'rest'.
183 * @return string Full URL to the endpoint.
185 function get_rest_url( $blog_id = null, $path = '/', $scheme = 'rest' ) {
186 if ( empty( $path ) ) {
190 if ( is_multisite() && get_blog_option( $blog_id, 'permalink_structure' ) || get_option( 'permalink_structure' ) ) {
191 $url = get_home_url( $blog_id, rest_get_url_prefix(), $scheme );
192 $url .= '/' . ltrim( $path, '/' );
194 $url = trailingslashit( get_home_url( $blog_id, '', $scheme ) );
196 $path = '/' . ltrim( $path, '/' );
198 $url = add_query_arg( 'rest_route', $path, $url );
202 // If the current host is the same as the REST URL host, force the REST URL scheme to HTTPS.
203 if ( $_SERVER['SERVER_NAME'] === parse_url( get_home_url( $blog_id ), PHP_URL_HOST ) ) {
204 $url = set_url_scheme( $url, 'https' );
209 * Filter the REST URL.
211 * Use this filter to adjust the url returned by the `get_rest_url` function.
215 * @param string $url REST URL.
216 * @param string $path REST route.
217 * @param int $blog_id Blog ID.
218 * @param string $scheme Sanitization scheme.
220 return apply_filters( 'rest_url', $url, $path, $blog_id, $scheme );
224 * Retrieves the URL to a REST endpoint.
226 * Note: The returned URL is NOT escaped.
230 * @param string $path Optional. REST route. Default empty.
231 * @param string $scheme Optional. Sanitization scheme. Default 'json'.
232 * @return string Full URL to the endpoint.
234 function rest_url( $path = '', $scheme = 'json' ) {
235 return get_rest_url( null, $path, $scheme );
241 * Used primarily to route internal requests through WP_REST_Server.
245 * @global WP_REST_Server $wp_rest_server ResponseHandler instance (usually WP_REST_Server).
247 * @param WP_REST_Request|string $request Request.
248 * @return WP_REST_Response REST response.
250 function rest_do_request( $request ) {
251 $request = rest_ensure_request( $request );
252 return rest_get_server()->dispatch( $request );
256 * Retrieves the current REST server instance.
258 * Instantiates a new instance if none exists already.
262 * @global WP_REST_Server $wp_rest_server REST server instance.
264 * @return WP_REST_Server REST server instance.
266 function rest_get_server() {
267 /* @var WP_REST_Server $wp_rest_server */
268 global $wp_rest_server;
270 if ( empty( $wp_rest_server ) ) {
272 * Filter the REST Server Class.
274 * This filter allows you to adjust the server class used by the API, using a
275 * different class to handle requests.
279 * @param string $class_name The name of the server class. Default 'WP_REST_Server'.
281 $wp_rest_server_class = apply_filters( 'wp_rest_server_class', 'WP_REST_Server' );
282 $wp_rest_server = new $wp_rest_server_class;
285 * Fires when preparing to serve an API request.
287 * Endpoint objects should be created and register their hooks on this action rather
288 * than another action to ensure they're only loaded when needed.
292 * @param WP_REST_Server $wp_rest_server Server object.
294 do_action( 'rest_api_init', $wp_rest_server );
297 return $wp_rest_server;
301 * Ensures request arguments are a request object (for consistency).
305 * @param array|WP_REST_Request $request Request to check.
306 * @return WP_REST_Request REST request instance.
308 function rest_ensure_request( $request ) {
309 if ( $request instanceof WP_REST_Request ) {
313 return new WP_REST_Request( 'GET', '', $request );
317 * Ensures a REST response is a response object (for consistency).
319 * This implements WP_HTTP_Response, allowing usage of `set_status`/`header`/etc
320 * without needing to double-check the object. Will also allow WP_Error to indicate error
321 * responses, so users should immediately check for this value.
325 * @param WP_Error|WP_HTTP_Response|mixed $response Response to check.
326 * @return mixed WP_Error if response generated an error, WP_HTTP_Response if response
327 * is a already an instance, otherwise returns a new WP_REST_Response instance.
329 function rest_ensure_response( $response ) {
330 if ( is_wp_error( $response ) ) {
334 if ( $response instanceof WP_HTTP_Response ) {
338 return new WP_REST_Response( $response );
342 * Handles _deprecated_function() errors.
346 * @param string $function The function that was called.
347 * @param string $replacement The function that should have been called.
348 * @param string $version Version.
350 function rest_handle_deprecated_function( $function, $replacement, $version ) {
351 if ( ! empty( $replacement ) ) {
352 /* translators: 1: function name, 2: WordPress version number, 3: new function name */
353 $string = sprintf( __( '%1$s (since %2$s; use %3$s instead)' ), $function, $version, $replacement );
355 /* translators: 1: function name, 2: WordPress version number */
356 $string = sprintf( __( '%1$s (since %2$s; no alternative available)' ), $function, $version );
359 header( sprintf( 'X-WP-DeprecatedFunction: %s', $string ) );
363 * Handles _deprecated_argument() errors.
367 * @param string $function The function that was called.
368 * @param string $message A message regarding the change.
369 * @param string $version Version.
371 function rest_handle_deprecated_argument( $function, $message, $version ) {
372 if ( ! empty( $message ) ) {
373 /* translators: 1: function name, 2: WordPress version number, 3: error message */
374 $string = sprintf( __( '%1$s (since %2$s; %3$s)' ), $function, $version, $message );
376 /* translators: 1: function name, 2: WordPress version number */
377 $string = sprintf( __( '%1$s (since %2$s; no alternative available)' ), $function, $version );
380 header( sprintf( 'X-WP-DeprecatedParam: %s', $string ) );
384 * Sends Cross-Origin Resource Sharing headers with API requests.
388 * @param mixed $value Response data.
389 * @return mixed Response data.
391 function rest_send_cors_headers( $value ) {
392 $origin = get_http_origin();
395 header( 'Access-Control-Allow-Origin: ' . esc_url_raw( $origin ) );
396 header( 'Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE' );
397 header( 'Access-Control-Allow-Credentials: true' );
404 * Handles OPTIONS requests for the server.
406 * This is handled outside of the server code, as it doesn't obey normal route
411 * @param mixed $response Current response, either response or `null` to indicate pass-through.
412 * @param WP_REST_Server $handler ResponseHandler instance (usually WP_REST_Server).
413 * @param WP_REST_Request $request The request that was used to make current response.
414 * @return WP_REST_Response Modified response, either response or `null` to indicate pass-through.
416 function rest_handle_options_request( $response, $handler, $request ) {
417 if ( ! empty( $response ) || $request->get_method() !== 'OPTIONS' ) {
421 $response = new WP_REST_Response();
426 foreach ( $handler->get_routes() as $route => $endpoints ) {
427 $match = preg_match( '@^' . $route . '$@i', $request->get_route(), $args );
433 $data = $handler->get_data_for_route( $route, $endpoints, 'help' );
434 $response->set_matched_route( $route );
438 $response->set_data( $data );
443 * Sends the "Allow" header to state all methods that can be sent to the current route.
447 * @param WP_REST_Response $response Current response being served.
448 * @param WP_REST_Server $server ResponseHandler instance (usually WP_REST_Server).
449 * @param WP_REST_Request $request The request that was used to make current response.
450 * @return WP_REST_Response Response to be served, with "Allow" header if route has allowed methods.
452 function rest_send_allow_header( $response, $server, $request ) {
453 $matched_route = $response->get_matched_route();
455 if ( ! $matched_route ) {
459 $routes = $server->get_routes();
461 $allowed_methods = array();
463 // Get the allowed methods across the routes.
464 foreach ( $routes[ $matched_route ] as $_handler ) {
465 foreach ( $_handler['methods'] as $handler_method => $value ) {
467 if ( ! empty( $_handler['permission_callback'] ) ) {
469 $permission = call_user_func( $_handler['permission_callback'], $request );
471 $allowed_methods[ $handler_method ] = true === $permission;
473 $allowed_methods[ $handler_method ] = true;
478 // Strip out all the methods that are not allowed (false values).
479 $allowed_methods = array_filter( $allowed_methods );
481 if ( $allowed_methods ) {
482 $response->header( 'Allow', implode( ', ', array_map( 'strtoupper', array_keys( $allowed_methods ) ) ) );
489 * Adds the REST API URL to the WP RSD endpoint.
493 * @see get_rest_url()
495 function rest_output_rsd() {
496 $api_root = get_rest_url();
498 if ( empty( $api_root ) ) {
502 <api name="WP-API" blogID="1" preferred="false" apiLink="<?php echo esc_url( $api_root ); ?>" />
507 * Outputs the REST API link tag into page header.
511 * @see get_rest_url()
513 function rest_output_link_wp_head() {
514 $api_root = get_rest_url();
516 if ( empty( $api_root ) ) {
520 echo "<link rel='https://api.w.org/' href='" . esc_url( $api_root ) . "' />\n";
524 * Sends a Link header for the REST API.
528 function rest_output_link_header() {
529 if ( headers_sent() ) {
533 $api_root = get_rest_url();
535 if ( empty( $api_root ) ) {
539 header( 'Link: <' . esc_url_raw( $api_root ) . '>; rel="https://api.w.org/"', false );
543 * Checks for errors when using cookie-based authentication.
545 * WordPress' built-in cookie authentication is always active
546 * for logged in users. However, the API has to check nonces
547 * for each request to ensure users are not vulnerable to CSRF.
551 * @global mixed $wp_rest_auth_cookie
553 * @param WP_Error|mixed $result Error from another authentication handler, null if we should handle it,
554 * or another value if not.
555 * @return WP_Error|mixed|bool WP_Error if the cookie is invalid, the $result, otherwise true.
557 function rest_cookie_check_errors( $result ) {
558 if ( ! empty( $result ) ) {
562 global $wp_rest_auth_cookie;
565 * Is cookie authentication being used? (If we get an auth
566 * error, but we're still logged in, another authentication
567 * must have been used).
569 if ( true !== $wp_rest_auth_cookie && is_user_logged_in() ) {
573 // Determine if there is a nonce.
576 if ( isset( $_REQUEST['_wpnonce'] ) ) {
577 $nonce = $_REQUEST['_wpnonce'];
578 } elseif ( isset( $_SERVER['HTTP_X_WP_NONCE'] ) ) {
579 $nonce = $_SERVER['HTTP_X_WP_NONCE'];
582 if ( null === $nonce ) {
583 // No nonce at all, so act as if it's an unauthenticated request.
584 wp_set_current_user( 0 );
589 $result = wp_verify_nonce( $nonce, 'wp_rest' );
592 return new WP_Error( 'rest_cookie_invalid_nonce', __( 'Cookie nonce is invalid' ), array( 'status' => 403 ) );
599 * Collects cookie authentication status.
601 * Collects errors from wp_validate_auth_cookie for use by rest_cookie_check_errors.
605 * @see current_action()
606 * @global mixed $wp_rest_auth_cookie
608 function rest_cookie_collect_status() {
609 global $wp_rest_auth_cookie;
611 $status_type = current_action();
613 if ( 'auth_cookie_valid' !== $status_type ) {
614 $wp_rest_auth_cookie = substr( $status_type, 12 );
618 $wp_rest_auth_cookie = true;
622 * Parses an RFC3339 time into a Unix timestamp.
626 * @param string $date RFC3339 timestamp.
627 * @param bool $force_utc Optional. Whether to force UTC timezone instead of using
628 * the timestamp's timezone. Default false.
629 * @return int Unix timestamp.
631 function rest_parse_date( $date, $force_utc = false ) {
633 $date = preg_replace( '/[+-]\d+:?\d+$/', '+00:00', $date );
636 $regex = '#^\d{4}-\d{2}-\d{2}[Tt ]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}(?::\d{2})?)?$#';
638 if ( ! preg_match( $regex, $date, $matches ) ) {
642 return strtotime( $date );
646 * Retrieves a local date with its GMT equivalent, in MySQL datetime format.
650 * @see rest_parse_date()
652 * @param string $date RFC3339 timestamp.
653 * @param bool $force_utc Whether a UTC timestamp should be forced. Default false.
654 * @return array|null Local and UTC datetime strings, in MySQL datetime format (Y-m-d H:i:s),
657 function rest_get_date_with_gmt( $date, $force_utc = false ) {
658 $date = rest_parse_date( $date, $force_utc );
660 if ( empty( $date ) ) {
664 $utc = date( 'Y-m-d H:i:s', $date );
665 $local = get_date_from_gmt( $utc );
667 return array( $local, $utc );