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 a new field on an existing WordPress object type.
78 * @global array $wp_rest_additional_fields Holds registered fields, organized
81 * @param string|array $object_type Object(s) the field is being registered
82 * to, "post"|"term"|"comment" etc.
83 * @param string $attribute The attribute name.
84 * @param array $args {
85 * Optional. An array of arguments used to handle the registered field.
87 * @type string|array|null $get_callback Optional. The callback function used to retrieve the field
88 * value. Default is 'null', the field will not be returned in
90 * @type string|array|null $update_callback Optional. The callback function used to set and update the
91 * field value. Default is 'null', the value cannot be set or
93 * @type string|array|null $schema Optional. The callback function used to create the schema for
94 * this field. Default is 'null', no schema entry will be returned.
97 function register_rest_field( $object_type, $attribute, $args = array() ) {
99 'get_callback' => null,
100 'update_callback' => null,
104 $args = wp_parse_args( $args, $defaults );
106 global $wp_rest_additional_fields;
108 $object_types = (array) $object_type;
110 foreach ( $object_types as $object_type ) {
111 $wp_rest_additional_fields[ $object_type ][ $attribute ] = $args;
116 * Registers rewrite rules for the API.
120 * @see rest_api_register_rewrites()
121 * @global WP $wp Current WordPress environment instance.
123 function rest_api_init() {
124 rest_api_register_rewrites();
127 $wp->add_query_var( 'rest_route' );
131 * Adds REST rewrite rules.
135 * @see add_rewrite_rule()
136 * @global WP_Rewrite $wp_rewrite
138 function rest_api_register_rewrites() {
141 add_rewrite_rule( '^' . rest_get_url_prefix() . '/?$','index.php?rest_route=/','top' );
142 add_rewrite_rule( '^' . rest_get_url_prefix() . '/(.*)?','index.php?rest_route=/$matches[1]','top' );
143 add_rewrite_rule( '^' . $wp_rewrite->index . '/' . rest_get_url_prefix() . '/?$','index.php?rest_route=/','top' );
144 add_rewrite_rule( '^' . $wp_rewrite->index . '/' . rest_get_url_prefix() . '/(.*)?','index.php?rest_route=/$matches[1]','top' );
148 * Registers the default REST API filters.
150 * Attached to the {@see 'rest_api_init'} action
151 * to make testing and disabling these filters easier.
155 function rest_api_default_filters() {
156 // Deprecated reporting.
157 add_action( 'deprecated_function_run', 'rest_handle_deprecated_function', 10, 3 );
158 add_filter( 'deprecated_function_trigger_error', '__return_false' );
159 add_action( 'deprecated_argument_run', 'rest_handle_deprecated_argument', 10, 3 );
160 add_filter( 'deprecated_argument_trigger_error', '__return_false' );
163 add_filter( 'rest_pre_serve_request', 'rest_send_cors_headers' );
164 add_filter( 'rest_post_dispatch', 'rest_send_allow_header', 10, 3 );
166 add_filter( 'rest_pre_dispatch', 'rest_handle_options_request', 10, 3 );
170 * Registers default REST API routes.
174 function create_initial_rest_routes() {
175 foreach ( get_post_types( array( 'show_in_rest' => true ), 'objects' ) as $post_type ) {
176 $class = ! empty( $post_type->rest_controller_class ) ? $post_type->rest_controller_class : 'WP_REST_Posts_Controller';
178 if ( ! class_exists( $class ) ) {
181 $controller = new $class( $post_type->name );
182 if ( ! is_subclass_of( $controller, 'WP_REST_Controller' ) ) {
186 $controller->register_routes();
188 if ( post_type_supports( $post_type->name, 'revisions' ) ) {
189 $revisions_controller = new WP_REST_Revisions_Controller( $post_type->name );
190 $revisions_controller->register_routes();
195 $controller = new WP_REST_Post_Types_Controller;
196 $controller->register_routes();
199 $controller = new WP_REST_Post_Statuses_Controller;
200 $controller->register_routes();
203 $controller = new WP_REST_Taxonomies_Controller;
204 $controller->register_routes();
207 foreach ( get_taxonomies( array( 'show_in_rest' => true ), 'object' ) as $taxonomy ) {
208 $class = ! empty( $taxonomy->rest_controller_class ) ? $taxonomy->rest_controller_class : 'WP_REST_Terms_Controller';
210 if ( ! class_exists( $class ) ) {
213 $controller = new $class( $taxonomy->name );
214 if ( ! is_subclass_of( $controller, 'WP_REST_Controller' ) ) {
218 $controller->register_routes();
222 $controller = new WP_REST_Users_Controller;
223 $controller->register_routes();
226 $controller = new WP_REST_Comments_Controller;
227 $controller->register_routes();
230 $controller = new WP_REST_Settings_Controller;
231 $controller->register_routes();
235 * Loads the REST API.
239 * @global WP $wp Current WordPress environment instance.
240 * @global WP_REST_Server $wp_rest_server ResponseHandler instance (usually WP_REST_Server).
242 function rest_api_loaded() {
243 if ( empty( $GLOBALS['wp']->query_vars['rest_route'] ) ) {
248 * Whether this is a REST Request.
253 define( 'REST_REQUEST', true );
255 // Initialize the server.
256 $server = rest_get_server();
258 // Fire off the request.
259 $server->serve_request( untrailingslashit( $GLOBALS['wp']->query_vars['rest_route'] ) );
266 * Retrieves the URL prefix for any API resource.
270 * @return string Prefix.
272 function rest_get_url_prefix() {
274 * Filters the REST URL prefix.
278 * @param string $prefix URL prefix. Default 'wp-json'.
280 return apply_filters( 'rest_url_prefix', 'wp-json' );
284 * Retrieves the URL to a REST endpoint on a site.
286 * Note: The returned URL is NOT escaped.
290 * @todo Check if this is even necessary
291 * @global WP_Rewrite $wp_rewrite
293 * @param int $blog_id Optional. Blog ID. Default of null returns URL for current blog.
294 * @param string $path Optional. REST route. Default '/'.
295 * @param string $scheme Optional. Sanitization scheme. Default 'rest'.
296 * @return string Full URL to the endpoint.
298 function get_rest_url( $blog_id = null, $path = '/', $scheme = 'rest' ) {
299 if ( empty( $path ) ) {
303 if ( is_multisite() && get_blog_option( $blog_id, 'permalink_structure' ) || get_option( 'permalink_structure' ) ) {
306 if ( $wp_rewrite->using_index_permalinks() ) {
307 $url = get_home_url( $blog_id, $wp_rewrite->index . '/' . rest_get_url_prefix(), $scheme );
309 $url = get_home_url( $blog_id, rest_get_url_prefix(), $scheme );
312 $url .= '/' . ltrim( $path, '/' );
314 $url = trailingslashit( get_home_url( $blog_id, '', $scheme ) );
316 $path = '/' . ltrim( $path, '/' );
318 $url = add_query_arg( 'rest_route', $path, $url );
322 // If the current host is the same as the REST URL host, force the REST URL scheme to HTTPS.
323 if ( $_SERVER['SERVER_NAME'] === parse_url( get_home_url( $blog_id ), PHP_URL_HOST ) ) {
324 $url = set_url_scheme( $url, 'https' );
329 * Filters the REST URL.
331 * Use this filter to adjust the url returned by the get_rest_url() function.
335 * @param string $url REST URL.
336 * @param string $path REST route.
337 * @param int $blog_id Blog ID.
338 * @param string $scheme Sanitization scheme.
340 return apply_filters( 'rest_url', $url, $path, $blog_id, $scheme );
344 * Retrieves the URL to a REST endpoint.
346 * Note: The returned URL is NOT escaped.
350 * @param string $path Optional. REST route. Default empty.
351 * @param string $scheme Optional. Sanitization scheme. Default 'json'.
352 * @return string Full URL to the endpoint.
354 function rest_url( $path = '', $scheme = 'json' ) {
355 return get_rest_url( null, $path, $scheme );
361 * Used primarily to route internal requests through WP_REST_Server.
365 * @global WP_REST_Server $wp_rest_server ResponseHandler instance (usually WP_REST_Server).
367 * @param WP_REST_Request|string $request Request.
368 * @return WP_REST_Response REST response.
370 function rest_do_request( $request ) {
371 $request = rest_ensure_request( $request );
372 return rest_get_server()->dispatch( $request );
376 * Retrieves the current REST server instance.
378 * Instantiates a new instance if none exists already.
382 * @global WP_REST_Server $wp_rest_server REST server instance.
384 * @return WP_REST_Server REST server instance.
386 function rest_get_server() {
387 /* @var WP_REST_Server $wp_rest_server */
388 global $wp_rest_server;
390 if ( empty( $wp_rest_server ) ) {
392 * Filters the REST Server Class.
394 * This filter allows you to adjust the server class used by the API, using a
395 * different class to handle requests.
399 * @param string $class_name The name of the server class. Default 'WP_REST_Server'.
401 $wp_rest_server_class = apply_filters( 'wp_rest_server_class', 'WP_REST_Server' );
402 $wp_rest_server = new $wp_rest_server_class;
405 * Fires when preparing to serve an API request.
407 * Endpoint objects should be created and register their hooks on this action rather
408 * than another action to ensure they're only loaded when needed.
412 * @param WP_REST_Server $wp_rest_server Server object.
414 do_action( 'rest_api_init', $wp_rest_server );
417 return $wp_rest_server;
421 * Ensures request arguments are a request object (for consistency).
425 * @param array|WP_REST_Request $request Request to check.
426 * @return WP_REST_Request REST request instance.
428 function rest_ensure_request( $request ) {
429 if ( $request instanceof WP_REST_Request ) {
433 return new WP_REST_Request( 'GET', '', $request );
437 * Ensures a REST response is a response object (for consistency).
439 * This implements WP_HTTP_Response, allowing usage of `set_status`/`header`/etc
440 * without needing to double-check the object. Will also allow WP_Error to indicate error
441 * responses, so users should immediately check for this value.
445 * @param WP_Error|WP_HTTP_Response|mixed $response Response to check.
446 * @return WP_REST_Response|mixed If response generated an error, WP_Error, if response
447 * is already an instance, WP_HTTP_Response, otherwise
448 * returns a new WP_REST_Response instance.
450 function rest_ensure_response( $response ) {
451 if ( is_wp_error( $response ) ) {
455 if ( $response instanceof WP_HTTP_Response ) {
459 return new WP_REST_Response( $response );
463 * Handles _deprecated_function() errors.
467 * @param string $function The function that was called.
468 * @param string $replacement The function that should have been called.
469 * @param string $version Version.
471 function rest_handle_deprecated_function( $function, $replacement, $version ) {
472 if ( ! empty( $replacement ) ) {
473 /* translators: 1: function name, 2: WordPress version number, 3: new function name */
474 $string = sprintf( __( '%1$s (since %2$s; use %3$s instead)' ), $function, $version, $replacement );
476 /* translators: 1: function name, 2: WordPress version number */
477 $string = sprintf( __( '%1$s (since %2$s; no alternative available)' ), $function, $version );
480 header( sprintf( 'X-WP-DeprecatedFunction: %s', $string ) );
484 * Handles _deprecated_argument() errors.
488 * @param string $function The function that was called.
489 * @param string $message A message regarding the change.
490 * @param string $version Version.
492 function rest_handle_deprecated_argument( $function, $message, $version ) {
493 if ( ! empty( $message ) ) {
494 /* translators: 1: function name, 2: WordPress version number, 3: error message */
495 $string = sprintf( __( '%1$s (since %2$s; %3$s)' ), $function, $version, $message );
497 /* translators: 1: function name, 2: WordPress version number */
498 $string = sprintf( __( '%1$s (since %2$s; no alternative available)' ), $function, $version );
501 header( sprintf( 'X-WP-DeprecatedParam: %s', $string ) );
505 * Sends Cross-Origin Resource Sharing headers with API requests.
509 * @param mixed $value Response data.
510 * @return mixed Response data.
512 function rest_send_cors_headers( $value ) {
513 $origin = get_http_origin();
516 header( 'Access-Control-Allow-Origin: ' . esc_url_raw( $origin ) );
517 header( 'Access-Control-Allow-Methods: OPTIONS, GET, POST, PUT, PATCH, DELETE' );
518 header( 'Access-Control-Allow-Credentials: true' );
519 header( 'Vary: Origin' );
526 * Handles OPTIONS requests for the server.
528 * This is handled outside of the server code, as it doesn't obey normal route
533 * @param mixed $response Current response, either response or `null` to indicate pass-through.
534 * @param WP_REST_Server $handler ResponseHandler instance (usually WP_REST_Server).
535 * @param WP_REST_Request $request The request that was used to make current response.
536 * @return WP_REST_Response Modified response, either response or `null` to indicate pass-through.
538 function rest_handle_options_request( $response, $handler, $request ) {
539 if ( ! empty( $response ) || $request->get_method() !== 'OPTIONS' ) {
543 $response = new WP_REST_Response();
546 foreach ( $handler->get_routes() as $route => $endpoints ) {
547 $match = preg_match( '@^' . $route . '$@i', $request->get_route() );
553 $data = $handler->get_data_for_route( $route, $endpoints, 'help' );
554 $response->set_matched_route( $route );
558 $response->set_data( $data );
563 * Sends the "Allow" header to state all methods that can be sent to the current route.
567 * @param WP_REST_Response $response Current response being served.
568 * @param WP_REST_Server $server ResponseHandler instance (usually WP_REST_Server).
569 * @param WP_REST_Request $request The request that was used to make current response.
570 * @return WP_REST_Response Response to be served, with "Allow" header if route has allowed methods.
572 function rest_send_allow_header( $response, $server, $request ) {
573 $matched_route = $response->get_matched_route();
575 if ( ! $matched_route ) {
579 $routes = $server->get_routes();
581 $allowed_methods = array();
583 // Get the allowed methods across the routes.
584 foreach ( $routes[ $matched_route ] as $_handler ) {
585 foreach ( $_handler['methods'] as $handler_method => $value ) {
587 if ( ! empty( $_handler['permission_callback'] ) ) {
589 $permission = call_user_func( $_handler['permission_callback'], $request );
591 $allowed_methods[ $handler_method ] = true === $permission;
593 $allowed_methods[ $handler_method ] = true;
598 // Strip out all the methods that are not allowed (false values).
599 $allowed_methods = array_filter( $allowed_methods );
601 if ( $allowed_methods ) {
602 $response->header( 'Allow', implode( ', ', array_map( 'strtoupper', array_keys( $allowed_methods ) ) ) );
609 * Adds the REST API URL to the WP RSD endpoint.
613 * @see get_rest_url()
615 function rest_output_rsd() {
616 $api_root = get_rest_url();
618 if ( empty( $api_root ) ) {
622 <api name="WP-API" blogID="1" preferred="false" apiLink="<?php echo esc_url( $api_root ); ?>" />
627 * Outputs the REST API link tag into page header.
631 * @see get_rest_url()
633 function rest_output_link_wp_head() {
634 $api_root = get_rest_url();
636 if ( empty( $api_root ) ) {
640 echo "<link rel='https://api.w.org/' href='" . esc_url( $api_root ) . "' />\n";
644 * Sends a Link header for the REST API.
648 function rest_output_link_header() {
649 if ( headers_sent() ) {
653 $api_root = get_rest_url();
655 if ( empty( $api_root ) ) {
659 header( 'Link: <' . esc_url_raw( $api_root ) . '>; rel="https://api.w.org/"', false );
663 * Checks for errors when using cookie-based authentication.
665 * WordPress' built-in cookie authentication is always active
666 * for logged in users. However, the API has to check nonces
667 * for each request to ensure users are not vulnerable to CSRF.
671 * @global mixed $wp_rest_auth_cookie
672 * @global WP_REST_Server $wp_rest_server REST server instance.
674 * @param WP_Error|mixed $result Error from another authentication handler,
675 * null if we should handle it, or another value
677 * @return WP_Error|mixed|bool WP_Error if the cookie is invalid, the $result, otherwise true.
679 function rest_cookie_check_errors( $result ) {
680 if ( ! empty( $result ) ) {
684 global $wp_rest_auth_cookie, $wp_rest_server;
687 * Is cookie authentication being used? (If we get an auth
688 * error, but we're still logged in, another authentication
689 * must have been used).
691 if ( true !== $wp_rest_auth_cookie && is_user_logged_in() ) {
695 // Determine if there is a nonce.
698 if ( isset( $_REQUEST['_wpnonce'] ) ) {
699 $nonce = $_REQUEST['_wpnonce'];
700 } elseif ( isset( $_SERVER['HTTP_X_WP_NONCE'] ) ) {
701 $nonce = $_SERVER['HTTP_X_WP_NONCE'];
704 if ( null === $nonce ) {
705 // No nonce at all, so act as if it's an unauthenticated request.
706 wp_set_current_user( 0 );
711 $result = wp_verify_nonce( $nonce, 'wp_rest' );
714 return new WP_Error( 'rest_cookie_invalid_nonce', __( 'Cookie nonce is invalid' ), array( 'status' => 403 ) );
717 // Send a refreshed nonce in header.
718 $wp_rest_server->send_header( 'X-WP-Nonce', wp_create_nonce( 'wp_rest' ) );
724 * Collects cookie authentication status.
726 * Collects errors from wp_validate_auth_cookie for use by rest_cookie_check_errors.
730 * @see current_action()
731 * @global mixed $wp_rest_auth_cookie
733 function rest_cookie_collect_status() {
734 global $wp_rest_auth_cookie;
736 $status_type = current_action();
738 if ( 'auth_cookie_valid' !== $status_type ) {
739 $wp_rest_auth_cookie = substr( $status_type, 12 );
743 $wp_rest_auth_cookie = true;
747 * Parses an RFC3339 time into a Unix timestamp.
751 * @param string $date RFC3339 timestamp.
752 * @param bool $force_utc Optional. Whether to force UTC timezone instead of using
753 * the timestamp's timezone. Default false.
754 * @return int Unix timestamp.
756 function rest_parse_date( $date, $force_utc = false ) {
758 $date = preg_replace( '/[+-]\d+:?\d+$/', '+00:00', $date );
761 $regex = '#^\d{4}-\d{2}-\d{2}[Tt ]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}(?::\d{2})?)?$#';
763 if ( ! preg_match( $regex, $date, $matches ) ) {
767 return strtotime( $date );
771 * Retrieves a local date with its GMT equivalent, in MySQL datetime format.
775 * @see rest_parse_date()
777 * @param string $date RFC3339 timestamp.
778 * @param bool $force_utc Whether a UTC timestamp should be forced. Default false.
779 * @return array|null Local and UTC datetime strings, in MySQL datetime format (Y-m-d H:i:s),
782 function rest_get_date_with_gmt( $date, $force_utc = false ) {
783 $date = rest_parse_date( $date, $force_utc );
785 if ( empty( $date ) ) {
789 $utc = date( 'Y-m-d H:i:s', $date );
790 $local = get_date_from_gmt( $utc );
792 return array( $local, $utc );
796 * Returns a contextual HTTP error code for authorization failure.
800 * @return integer 401 if the user is not logged in, 403 if the user is logged in.
802 function rest_authorization_required_code() {
803 return is_user_logged_in() ? 403 : 401;
807 * Validate a request argument based on details registered to the route.
811 * @param mixed $value
812 * @param WP_REST_Request $request
813 * @param string $param
814 * @return WP_Error|boolean
816 function rest_validate_request_arg( $value, $request, $param ) {
817 $attributes = $request->get_attributes();
818 if ( ! isset( $attributes['args'][ $param ] ) || ! is_array( $attributes['args'][ $param ] ) ) {
821 $args = $attributes['args'][ $param ];
823 return rest_validate_value_from_schema( $value, $args, $param );
827 * Sanitize a request argument based on details registered to the route.
831 * @param mixed $value
832 * @param WP_REST_Request $request
833 * @param string $param
836 function rest_sanitize_request_arg( $value, $request, $param ) {
837 $attributes = $request->get_attributes();
838 if ( ! isset( $attributes['args'][ $param ] ) || ! is_array( $attributes['args'][ $param ] ) ) {
841 $args = $attributes['args'][ $param ];
843 return rest_sanitize_value_from_schema( $value, $args );
847 * Parse a request argument based on details registered to the route.
849 * Runs a validation check and sanitizes the value, primarily to be used via
850 * the `sanitize_callback` arguments in the endpoint args registration.
854 * @param mixed $value
855 * @param WP_REST_Request $request
856 * @param string $param
859 function rest_parse_request_arg( $value, $request, $param ) {
860 $is_valid = rest_validate_request_arg( $value, $request, $param );
862 if ( is_wp_error( $is_valid ) ) {
866 $value = rest_sanitize_request_arg( $value, $request, $param );
872 * Determines if an IP address is valid.
874 * Handles both IPv4 and IPv6 addresses.
878 * @param string $ip IP address.
879 * @return string|false The valid IP address, otherwise false.
881 function rest_is_ip_address( $ip ) {
882 $ipv4_pattern = '/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/';
884 if ( ! preg_match( $ipv4_pattern, $ip ) && ! Requests_IPv6::check_ipv6( $ip ) ) {
892 * Changes a boolean-like value into the proper boolean value.
896 * @param bool|string|int $value The value being evaluated.
897 * @return boolean Returns the proper associated boolean value.
899 function rest_sanitize_boolean( $value ) {
900 // String values are translated to `true`; make sure 'false' is false.
901 if ( is_string( $value ) ) {
902 $value = strtolower( $value );
903 if ( in_array( $value, array( 'false', '0' ), true ) ) {
908 // Everything else will map nicely to boolean.
909 return (boolean) $value;
913 * Determines if a given value is boolean-like.
917 * @param bool|string $maybe_bool The value being evaluated.
918 * @return boolean True if a boolean, otherwise false.
920 function rest_is_boolean( $maybe_bool ) {
921 if ( is_bool( $maybe_bool ) ) {
925 if ( is_string( $maybe_bool ) ) {
926 $maybe_bool = strtolower( $maybe_bool );
928 $valid_boolean_values = array(
935 return in_array( $maybe_bool, $valid_boolean_values, true );
938 if ( is_int( $maybe_bool ) ) {
939 return in_array( $maybe_bool, array( 0, 1 ), true );
946 * Retrieves the avatar urls in various sizes based on a given email address.
950 * @see get_avatar_url()
952 * @param string $email Email address.
953 * @return array $urls Gravatar url for each size.
955 function rest_get_avatar_urls( $email ) {
956 $avatar_sizes = rest_get_avatar_sizes();
959 foreach ( $avatar_sizes as $size ) {
960 $urls[ $size ] = get_avatar_url( $email, array( 'size' => $size ) );
967 * Retrieves the pixel sizes for avatars.
971 * @return array List of pixel sizes for avatars. Default `[ 24, 48, 96 ]`.
973 function rest_get_avatar_sizes() {
975 * Filter the REST avatar sizes.
977 * Use this filter to adjust the array of sizes returned by the
978 * `rest_get_avatar_sizes` function.
982 * @param array $sizes An array of int values that are the pixel sizes for avatars.
983 * Default `[ 24, 48, 96 ]`.
985 return apply_filters( 'rest_avatar_sizes', array( 24, 48, 96 ) );
989 * Validate a value based on a schema.
991 * @param mixed $value The value to validate.
992 * @param array $args Schema array to use for validation.
993 * @param string $param The parameter name, used in error messages.
994 * @return true|WP_Error
996 function rest_validate_value_from_schema( $value, $args, $param = '' ) {
997 if ( 'array' === $args['type'] ) {
998 if ( ! is_array( $value ) ) {
999 $value = preg_split( '/[\s,]+/', $value );
1001 if ( ! wp_is_numeric_array( $value ) ) {
1002 /* translators: 1: parameter, 2: type name */
1003 return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s is not of type %2$s.' ), $param, 'array' ) );
1005 foreach ( $value as $index => $v ) {
1006 $is_valid = rest_validate_value_from_schema( $v, $args['items'], $param . '[' . $index . ']' );
1007 if ( is_wp_error( $is_valid ) ) {
1012 if ( ! empty( $args['enum'] ) ) {
1013 if ( ! in_array( $value, $args['enum'], true ) ) {
1014 /* translators: 1: parameter, 2: list of valid values */
1015 return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s is not one of %2$s.' ), $param, implode( ', ', $args['enum'] ) ) );
1019 if ( in_array( $args['type'], array( 'integer', 'number' ) ) && ! is_numeric( $value ) ) {
1020 /* translators: 1: parameter, 2: type name */
1021 return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s is not of type %2$s.' ), $param, $args['type'] ) );
1024 if ( 'integer' === $args['type'] && round( floatval( $value ) ) !== floatval( $value ) ) {
1025 /* translators: 1: parameter, 2: type name */
1026 return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s is not of type %2$s.' ), $param, 'integer' ) );
1029 if ( 'boolean' === $args['type'] && ! rest_is_boolean( $value ) ) {
1030 /* translators: 1: parameter, 2: type name */
1031 return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s is not of type %2$s.' ), $value, 'boolean' ) );
1034 if ( 'string' === $args['type'] && ! is_string( $value ) ) {
1035 /* translators: 1: parameter, 2: type name */
1036 return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s is not of type %2$s.' ), $param, 'string' ) );
1039 if ( isset( $args['format'] ) ) {
1040 switch ( $args['format'] ) {
1042 if ( ! rest_parse_date( $value ) ) {
1043 return new WP_Error( 'rest_invalid_date', __( 'Invalid date.' ) );
1048 // is_email() checks for 3 characters (a@b), but
1049 // wp_handle_comment_submission() requires 6 characters (a@b.co)
1051 // https://core.trac.wordpress.org/ticket/38506
1052 if ( ! is_email( $value ) || strlen( $value ) < 6 ) {
1053 return new WP_Error( 'rest_invalid_email', __( 'Invalid email address.' ) );
1057 if ( ! rest_is_ip_address( $value ) ) {
1058 /* translators: %s: IP address */
1059 return new WP_Error( 'rest_invalid_param', sprintf( __( '%s is not a valid IP address.' ), $value ) );
1065 if ( in_array( $args['type'], array( 'number', 'integer' ), true ) && ( isset( $args['minimum'] ) || isset( $args['maximum'] ) ) ) {
1066 if ( isset( $args['minimum'] ) && ! isset( $args['maximum'] ) ) {
1067 if ( ! empty( $args['exclusiveMinimum'] ) && $value <= $args['minimum'] ) {
1068 /* translators: 1: parameter, 2: minimum number */
1069 return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s must be greater than %2$d (exclusive)' ), $param, $args['minimum'] ) );
1070 } elseif ( empty( $args['exclusiveMinimum'] ) && $value < $args['minimum'] ) {
1071 /* translators: 1: parameter, 2: minimum number */
1072 return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s must be greater than %2$d (inclusive)' ), $param, $args['minimum'] ) );
1074 } elseif ( isset( $args['maximum'] ) && ! isset( $args['minimum'] ) ) {
1075 if ( ! empty( $args['exclusiveMaximum'] ) && $value >= $args['maximum'] ) {
1076 /* translators: 1: parameter, 2: maximum number */
1077 return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s must be less than %2$d (exclusive)' ), $param, $args['maximum'] ) );
1078 } elseif ( empty( $args['exclusiveMaximum'] ) && $value > $args['maximum'] ) {
1079 /* translators: 1: parameter, 2: maximum number */
1080 return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s must be less than %2$d (inclusive)' ), $param, $args['maximum'] ) );
1082 } elseif ( isset( $args['maximum'] ) && isset( $args['minimum'] ) ) {
1083 if ( ! empty( $args['exclusiveMinimum'] ) && ! empty( $args['exclusiveMaximum'] ) ) {
1084 if ( $value >= $args['maximum'] || $value <= $args['minimum'] ) {
1085 /* translators: 1: parameter, 2: minimum number, 3: maximum number */
1086 return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s must be between %2$d (exclusive) and %3$d (exclusive)' ), $param, $args['minimum'], $args['maximum'] ) );
1088 } elseif ( empty( $args['exclusiveMinimum'] ) && ! empty( $args['exclusiveMaximum'] ) ) {
1089 if ( $value >= $args['maximum'] || $value < $args['minimum'] ) {
1090 /* translators: 1: parameter, 2: minimum number, 3: maximum number */
1091 return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s must be between %2$d (inclusive) and %3$d (exclusive)' ), $param, $args['minimum'], $args['maximum'] ) );
1093 } elseif ( ! empty( $args['exclusiveMinimum'] ) && empty( $args['exclusiveMaximum'] ) ) {
1094 if ( $value > $args['maximum'] || $value <= $args['minimum'] ) {
1095 /* translators: 1: parameter, 2: minimum number, 3: maximum number */
1096 return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s must be between %2$d (exclusive) and %3$d (inclusive)' ), $param, $args['minimum'], $args['maximum'] ) );
1098 } elseif ( empty( $args['exclusiveMinimum'] ) && empty( $args['exclusiveMaximum'] ) ) {
1099 if ( $value > $args['maximum'] || $value < $args['minimum'] ) {
1100 /* translators: 1: parameter, 2: minimum number, 3: maximum number */
1101 return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s must be between %2$d (inclusive) and %3$d (inclusive)' ), $param, $args['minimum'], $args['maximum'] ) );
1111 * Sanitize a value based on a schema.
1113 * @param mixed $value The value to sanitize.
1114 * @param array $args Schema array to use for sanitization.
1115 * @return true|WP_Error
1117 function rest_sanitize_value_from_schema( $value, $args ) {
1118 if ( 'array' === $args['type'] ) {
1119 if ( empty( $args['items'] ) ) {
1120 return (array) $value;
1122 if ( ! is_array( $value ) ) {
1123 $value = preg_split( '/[\s,]+/', $value );
1125 foreach ( $value as $index => $v ) {
1126 $value[ $index ] = rest_sanitize_value_from_schema( $v, $args['items'] );
1128 // Normalize to numeric array so nothing unexpected
1130 $value = array_values( $value );
1133 if ( 'integer' === $args['type'] ) {
1134 return (int) $value;
1137 if ( 'number' === $args['type'] ) {
1138 return (float) $value;
1141 if ( 'boolean' === $args['type'] ) {
1142 return rest_sanitize_boolean( $value );
1145 if ( isset( $args['format'] ) ) {
1146 switch ( $args['format'] ) {
1148 return sanitize_text_field( $value );
1152 * sanitize_email() validates, which would be unexpected.
1154 return sanitize_text_field( $value );
1157 return esc_url_raw( $value );
1160 return sanitize_text_field( $value );
1164 if ( 'string' === $args['type'] ) {
1165 return strval( $value );