WP_REST_Meta_Fields::update_value

Advertisement

Summery Summery

Updates meta values.

Syntax Syntax

WP_REST_Meta_Fields::update_value( array $meta, int $object_id )

Parameters Parameters

$meta

(Required) Array of meta parsed from the request.

$object_id

(Required) Object ID to fetch meta for.

Return Return

(null|WP_Error) Null on success, WP_Error object on failure.

Source Source

File: wp-includes/rest-api/fields/class-wp-rest-meta-fields.php

	public function update_value( $meta, $object_id ) {
		$fields = $this->get_registered_fields();

		foreach ( $fields as $meta_key => $args ) {
			$name = $args['name'];
			if ( ! array_key_exists( $name, $meta ) ) {
				continue;
			}

			/*
			 * A null value means reset the field, which is essentially deleting it
			 * from the database and then relying on the default value.
			 */
			if ( is_null( $meta[ $name ] ) ) {
				$args = $this->get_registered_fields()[ $meta_key ];

				if ( $args['single'] ) {
					$current = get_metadata( $this->get_meta_type(), $object_id, $meta_key, true );

					if ( is_wp_error( rest_validate_value_from_schema( $current, $args['schema'] ) ) ) {
						return new WP_Error(
							'rest_invalid_stored_value',
							/* translators: %s: Custom field key. */
							sprintf( __( 'The %s property has an invalid stored value, and cannot be updated to null.' ), $name ),
							array( 'status' => 500 )
						);
					}
				}

				$result = $this->delete_meta_value( $object_id, $meta_key, $name );
				if ( is_wp_error( $result ) ) {
					return $result;
				}
				continue;
			}

			$value = $meta[ $name ];

			if ( ! $args['single'] && is_array( $value ) && count( array_filter( $value, 'is_null' ) ) ) {
				return new WP_Error(
					'rest_invalid_stored_value',
					/* translators: %s: Custom field key. */
					sprintf( __( 'The %s property has an invalid stored value, and cannot be updated to null.' ), $name ),
					array( 'status' => 500 )
				);
			}

			$is_valid = rest_validate_value_from_schema( $value, $args['schema'], 'meta.' . $name );
			if ( is_wp_error( $is_valid ) ) {
				$is_valid->add_data( array( 'status' => 400 ) );
				return $is_valid;
			}

			$value = rest_sanitize_value_from_schema( $value, $args['schema'] );

			if ( $args['single'] ) {
				$result = $this->update_meta_value( $object_id, $meta_key, $name, $value );
			} else {
				$result = $this->update_multi_meta_value( $object_id, $meta_key, $name, $value );
			}

			if ( is_wp_error( $result ) ) {
				return $result;
			}
		}

		return null;
	}

Advertisement

Changelog Changelog

Changelog
Version Description
4.7.0 Introduced.

Advertisement

Leave a Reply