WP_REST_Settings_Controller::update_item( WP_REST_Request $request ): array|WP_Error

In this article

Updates settings for the settings object.

Parameters

$requestWP_REST_Requestrequired
Full details about the request.

Return

array|WP_Error Array on success, or error object on failure.

Source

public function update_item( $request ) {
	$options = $this->get_registered_options();

	$params = $request->get_params();

	foreach ( $options as $name => $args ) {
		if ( ! array_key_exists( $name, $params ) ) {
			continue;
		}

		/**
		 * Filters whether to preempt a setting value update via the REST API.
		 *
		 * Allows hijacking the setting update logic and overriding the built-in behavior by
		 * returning true.
		 *
		 * @since 4.7.0
		 *
		 * @param bool   $result Whether to override the default behavior for updating the
		 *                       value of a setting.
		 * @param string $name   Setting name (as shown in REST API responses).
		 * @param mixed  $value  Updated setting value.
		 * @param array  $args   Arguments passed to register_setting() for this setting.
		 */
		$updated = apply_filters( 'rest_pre_update_setting', false, $name, $request[ $name ], $args );

		if ( $updated ) {
			continue;
		}

		/*
		 * A null value for an option would have the same effect as
		 * deleting the option from the database, and relying on the
		 * default value.
		 */
		if ( is_null( $request[ $name ] ) ) {
			/*
			 * A null value is returned in the response for any option
			 * that has a non-scalar value.
			 *
			 * To protect clients from accidentally including the null
			 * values from a response object in a request, we do not allow
			 * options with values that don't pass validation to be updated to null.
			 * Without this added protection a client could mistakenly
			 * delete all options that have invalid values from the
			 * database.
			 */
			if ( is_wp_error( rest_validate_value_from_schema( get_option( $args['option_name'], false ), $args['schema'] ) ) ) {
				return new WP_Error(
					'rest_invalid_stored_value',
					/* translators: %s: Property name. */
					sprintf( __( 'The %s property has an invalid stored value, and cannot be updated to null.' ), $name ),
					array( 'status' => 500 )
				);
			}

			delete_option( $args['option_name'] );
		} else {
			update_option( $args['option_name'], $request[ $name ] );
		}
	}

	return $this->get_item( $request );
}

Hooks

apply_filters( ‘rest_pre_update_setting’, bool $result, string $name, mixed $value, array $args )

Filters whether to preempt a setting value update via the REST API.

Changelog

VersionDescription
4.7.0Introduced.

User Contributed Notes

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