WP_REST_Request::sanitize_params()

Sanitizes (where possible) the params on the request.


Description Description

This is primarily based off the sanitize_callback param on each registered argument.


Return Return

(true|WP_Error) True if parameters were sanitized, WP_Error if an error occurred during sanitization.


Top ↑

Source Source

File: wp-includes/rest-api/class-wp-rest-request.php

	public function sanitize_params() {
		$attributes = $this->get_attributes();

		// No arguments set, skip sanitizing.
		if ( empty( $attributes['args'] ) ) {
			return true;
		}

		$order = $this->get_parameter_order();

		$invalid_params = array();

		foreach ( $order as $type ) {
			if ( empty( $this->params[ $type ] ) ) {
				continue;
			}
			foreach ( $this->params[ $type ] as $key => $value ) {
				if ( ! isset( $attributes['args'][ $key ] ) ) {
					continue;
				}
				$param_args = $attributes['args'][ $key ];

				// If the arg has a type but no sanitize_callback attribute, default to rest_parse_request_arg.
				if ( ! array_key_exists( 'sanitize_callback', $param_args ) && ! empty( $param_args['type'] ) ) {
					$param_args['sanitize_callback'] = 'rest_parse_request_arg';
				}
				// If there's still no sanitize_callback, nothing to do here.
				if ( empty( $param_args['sanitize_callback'] ) ) {
					continue;
				}

				$sanitized_value = call_user_func( $param_args['sanitize_callback'], $value, $this, $key );

				if ( is_wp_error( $sanitized_value ) ) {
					$invalid_params[ $key ] = $sanitized_value->get_error_message();
				} else {
					$this->params[ $type ][ $key ] = $sanitized_value;
				}
			}
		}

		if ( $invalid_params ) {
			return new WP_Error(
				'rest_invalid_param',
				/* translators: %s: List of invalid parameters. */
				sprintf( __( 'Invalid parameter(s): %s' ), implode( ', ', array_keys( $invalid_params ) ) ),
				array(
					'status' => 400,
					'params' => $invalid_params,
				)
			);
		}

		return true;
	}

Top ↑

Changelog Changelog

Changelog
Version Description
4.4.0 Introduced.


Top ↑

User Contributed Notes User Contributed Notes

You must log in before being able to contribute a note or feedback.