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 /** @var WP_REST_Server $wp_rest_server */
144 global $wp_rest_server;
147 * Filter the REST Server Class.
149 * This filter allows you to adjust the server class used by the API, using a
150 * different class to handle requests.
154 * @param string $class_name The name of the server class. Default 'WP_REST_Server'.
156 $wp_rest_server_class = apply_filters( 'wp_rest_server_class', 'WP_REST_Server' );
157 $wp_rest_server = new $wp_rest_server_class;
160 * Fires when preparing to serve an API request.
162 * Endpoint objects should be created and register their hooks on this action rather
163 * than another action to ensure they're only loaded when needed.
167 * @param WP_REST_Server $wp_rest_server Server object.
169 do_action( 'rest_api_init', $wp_rest_server );
171 // Fire off the request.
172 $wp_rest_server->serve_request( $GLOBALS['wp']->query_vars['rest_route'] );
179 * Retrieves the URL prefix for any API resource.
183 * @return string Prefix.
185 function rest_get_url_prefix() {
187 * Filter the REST URL prefix.
191 * @param string $prefix URL prefix. Default 'wp-json'.
193 return apply_filters( 'rest_url_prefix', 'wp-json' );
197 * Retrieves the URL to a REST endpoint on a site.
199 * Note: The returned URL is NOT escaped.
203 * @todo Check if this is even necessary
205 * @param int $blog_id Optional. Blog ID. Default of null returns URL for current blog.
206 * @param string $path Optional. REST route. Default '/'.
207 * @param string $scheme Optional. Sanitization scheme. Default 'rest'.
208 * @return string Full URL to the endpoint.
210 function get_rest_url( $blog_id = null, $path = '/', $scheme = 'rest' ) {
211 if ( empty( $path ) ) {
215 if ( is_multisite() && get_blog_option( $blog_id, 'permalink_structure' ) || get_option( 'permalink_structure' ) ) {
216 $url = get_home_url( $blog_id, rest_get_url_prefix(), $scheme );
217 $url .= '/' . ltrim( $path, '/' );
219 $url = trailingslashit( get_home_url( $blog_id, '', $scheme ) );
221 $path = '/' . ltrim( $path, '/' );
223 $url = add_query_arg( 'rest_route', $path, $url );
227 // If the current host is the same as the REST URL host, force the REST URL scheme to HTTPS.
228 if ( $_SERVER['SERVER_NAME'] === parse_url( get_home_url( $blog_id ), PHP_URL_HOST ) ) {
229 $url = set_url_scheme( $url, 'https' );
234 * Filter the REST URL.
236 * Use this filter to adjust the url returned by the `get_rest_url` function.
240 * @param string $url REST URL.
241 * @param string $path REST route.
242 * @param int $blog_id Blog ID.
243 * @param string $scheme Sanitization scheme.
245 return apply_filters( 'rest_url', $url, $path, $blog_id, $scheme );
249 * Retrieves the URL to a REST endpoint.
251 * Note: The returned URL is NOT escaped.
255 * @param string $path Optional. REST route. Default empty.
256 * @param string $scheme Optional. Sanitization scheme. Default 'json'.
257 * @return string Full URL to the endpoint.
259 function rest_url( $path = '', $scheme = 'json' ) {
260 return get_rest_url( null, $path, $scheme );
266 * Used primarily to route internal requests through WP_REST_Server.
270 * @global WP_REST_Server $wp_rest_server ResponseHandler instance (usually WP_REST_Server).
272 * @param WP_REST_Request|string $request Request.
273 * @return WP_REST_Response REST response.
275 function rest_do_request( $request ) {
276 global $wp_rest_server;
277 $request = rest_ensure_request( $request );
278 return $wp_rest_server->dispatch( $request );
282 * Ensures request arguments are a request object (for consistency).
286 * @param array|WP_REST_Request $request Request to check.
287 * @return WP_REST_Request REST request instance.
289 function rest_ensure_request( $request ) {
290 if ( $request instanceof WP_REST_Request ) {
294 return new WP_REST_Request( 'GET', '', $request );
298 * Ensures a REST response is a response object (for consistency).
300 * This implements WP_HTTP_Response, allowing usage of `set_status`/`header`/etc
301 * without needing to double-check the object. Will also allow WP_Error to indicate error
302 * responses, so users should immediately check for this value.
306 * @param WP_Error|WP_HTTP_Response|mixed $response Response to check.
307 * @return mixed WP_Error if response generated an error, WP_HTTP_Response if response
308 * is a already an instance, otherwise returns a new WP_REST_Response instance.
310 function rest_ensure_response( $response ) {
311 if ( is_wp_error( $response ) ) {
315 if ( $response instanceof WP_HTTP_Response ) {
319 return new WP_REST_Response( $response );
323 * Handles _deprecated_function() errors.
327 * @param string $function Function name.
328 * @param string $replacement Replacement function name.
329 * @param string $version Version.
331 function rest_handle_deprecated_function( $function, $replacement, $version ) {
332 if ( ! empty( $replacement ) ) {
333 /* translators: 1: function name, 2: WordPress version number, 3: new function name */
334 $string = sprintf( __( '%1$s (since %2$s; use %3$s instead)' ), $function, $version, $replacement );
336 /* translators: 1: function name, 2: WordPress version number */
337 $string = sprintf( __( '%1$s (since %2$s; no alternative available)' ), $function, $version );
340 header( sprintf( 'X-WP-DeprecatedFunction: %s', $string ) );
344 * Handles _deprecated_argument() errors.
348 * @param string $function Function name.
349 * @param string $replacement Replacement function name.
350 * @param string $version Version.
352 function rest_handle_deprecated_argument( $function, $replacement, $version ) {
353 if ( ! empty( $replacement ) ) {
354 /* translators: 1: function name, 2: WordPress version number, 3: new argument name */
355 $string = sprintf( __( '%1$s (since %2$s; %3$s)' ), $function, $version, $replacement );
357 /* translators: 1: function name, 2: WordPress version number */
358 $string = sprintf( __( '%1$s (since %2$s; no alternative available)' ), $function, $version );
361 header( sprintf( 'X-WP-DeprecatedParam: %s', $string ) );
365 * Sends Cross-Origin Resource Sharing headers with API requests.
369 * @param mixed $value Response data.
370 * @return mixed Response data.
372 function rest_send_cors_headers( $value ) {
373 $origin = get_http_origin();
376 header( 'Access-Control-Allow-Origin: ' . esc_url_raw( $origin ) );
377 header( 'Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE' );
378 header( 'Access-Control-Allow-Credentials: true' );
385 * Handles OPTIONS requests for the server.
387 * This is handled outside of the server code, as it doesn't obey normal route
392 * @param mixed $response Current response, either response or `null` to indicate pass-through.
393 * @param WP_REST_Server $handler ResponseHandler instance (usually WP_REST_Server).
394 * @param WP_REST_Request $request The request that was used to make current response.
395 * @return WP_REST_Response Modified response, either response or `null` to indicate pass-through.
397 function rest_handle_options_request( $response, $handler, $request ) {
398 if ( ! empty( $response ) || $request->get_method() !== 'OPTIONS' ) {
402 $response = new WP_REST_Response();
407 foreach ( $handler->get_routes() as $route => $endpoints ) {
408 $match = preg_match( '@^' . $route . '$@i', $request->get_route(), $args );
414 $data = $handler->get_data_for_route( $route, $endpoints, 'help' );
415 $accept = array_merge( $accept, $data['methods'] );
418 $response->header( 'Accept', implode( ', ', $accept ) );
420 $response->set_data( $data );
425 * Sends the "Allow" header to state all methods that can be sent to the current route.
429 * @param WP_REST_Response $response Current response being served.
430 * @param WP_REST_Server $server ResponseHandler instance (usually WP_REST_Server).
431 * @param WP_REST_Request $request The request that was used to make current response.
432 * @return WP_REST_Response Response to be served, with "Allow" header if route has allowed methods.
434 function rest_send_allow_header( $response, $server, $request ) {
435 $matched_route = $response->get_matched_route();
437 if ( ! $matched_route ) {
441 $routes = $server->get_routes();
443 $allowed_methods = array();
445 // Get the allowed methods across the routes.
446 foreach ( $routes[ $matched_route ] as $_handler ) {
447 foreach ( $_handler['methods'] as $handler_method => $value ) {
449 if ( ! empty( $_handler['permission_callback'] ) ) {
451 $permission = call_user_func( $_handler['permission_callback'], $request );
453 $allowed_methods[ $handler_method ] = true === $permission;
455 $allowed_methods[ $handler_method ] = true;
460 // Strip out all the methods that are not allowed (false values).
461 $allowed_methods = array_filter( $allowed_methods );
463 if ( $allowed_methods ) {
464 $response->header( 'Allow', implode( ', ', array_map( 'strtoupper', array_keys( $allowed_methods ) ) ) );
471 * Adds the REST API URL to the WP RSD endpoint.
475 * @see get_rest_url()
477 function rest_output_rsd() {
478 $api_root = get_rest_url();
480 if ( empty( $api_root ) ) {
484 <api name="WP-API" blogID="1" preferred="false" apiLink="<?php echo esc_url( $api_root ); ?>" />
489 * Outputs the REST API link tag into page header.
493 * @see get_rest_url()
495 function rest_output_link_wp_head() {
496 $api_root = get_rest_url();
498 if ( empty( $api_root ) ) {
502 echo "<link rel='https://api.w.org/' href='" . esc_url( $api_root ) . "' />\n";
506 * Sends a Link header for the REST API.
510 function rest_output_link_header() {
511 if ( headers_sent() ) {
515 $api_root = get_rest_url();
517 if ( empty( $api_root ) ) {
521 header( 'Link: <' . esc_url_raw( $api_root ) . '>; rel="https://api.w.org/"', false );
525 * Checks for errors when using cookie-based authentication.
527 * WordPress' built-in cookie authentication is always active
528 * for logged in users. However, the API has to check nonces
529 * for each request to ensure users are not vulnerable to CSRF.
533 * @global mixed $wp_rest_auth_cookie
535 * @param WP_Error|mixed $result Error from another authentication handler, null if we should handle it,
536 * or another value if not.
537 * @return WP_Error|mixed|bool WP_Error if the cookie is invalid, the $result, otherwise true.
539 function rest_cookie_check_errors( $result ) {
540 if ( ! empty( $result ) ) {
544 global $wp_rest_auth_cookie;
547 * Is cookie authentication being used? (If we get an auth
548 * error, but we're still logged in, another authentication
549 * must have been used).
551 if ( true !== $wp_rest_auth_cookie && is_user_logged_in() ) {
555 // Determine if there is a nonce.
558 if ( isset( $_REQUEST['_wpnonce'] ) ) {
559 $nonce = $_REQUEST['_wpnonce'];
560 } elseif ( isset( $_SERVER['HTTP_X_WP_NONCE'] ) ) {
561 $nonce = $_SERVER['HTTP_X_WP_NONCE'];
564 if ( null === $nonce ) {
565 // No nonce at all, so act as if it's an unauthenticated request.
566 wp_set_current_user( 0 );
571 $result = wp_verify_nonce( $nonce, 'wp_rest' );
574 return new WP_Error( 'rest_cookie_invalid_nonce', __( 'Cookie nonce is invalid' ), array( 'status' => 403 ) );
581 * Collects cookie authentication status.
583 * Collects errors from wp_validate_auth_cookie for use by rest_cookie_check_errors.
587 * @see current_action()
588 * @global mixed $wp_rest_auth_cookie
590 function rest_cookie_collect_status() {
591 global $wp_rest_auth_cookie;
593 $status_type = current_action();
595 if ( 'auth_cookie_valid' !== $status_type ) {
596 $wp_rest_auth_cookie = substr( $status_type, 12 );
600 $wp_rest_auth_cookie = true;
604 * Parses an RFC3339 timestamp into a DateTime.
608 * @param string $date RFC3339 timestamp.
609 * @param bool $force_utc Optional. Whether to force UTC timezone instead of using
610 * the timestamp's timezone. Default false.
611 * @return DateTime DateTime instance.
613 function rest_parse_date( $date, $force_utc = false ) {
615 $date = preg_replace( '/[+-]\d+:?\d+$/', '+00:00', $date );
618 $regex = '#^\d{4}-\d{2}-\d{2}[Tt ]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}(?::\d{2})?)?$#';
620 if ( ! preg_match( $regex, $date, $matches ) ) {
624 return strtotime( $date );
628 * Retrieves a local date with its GMT equivalent, in MySQL datetime format.
632 * @see rest_parse_date()
634 * @param string $date RFC3339 timestamp.
635 * @param bool $force_utc Whether a UTC timestamp should be forced. Default false.
636 * @return array|null Local and UTC datetime strings, in MySQL datetime format (Y-m-d H:i:s),
639 function rest_get_date_with_gmt( $date, $force_utc = false ) {
640 $date = rest_parse_date( $date, $force_utc );
642 if ( empty( $date ) ) {
646 $utc = date( 'Y-m-d H:i:s', $date );
647 $local = get_date_from_gmt( $utc );
649 return array( $local, $utc );