WP-API / docs

The content for developer.wordpress.org/rest-api

Home Page:https://developer.wordpress.org/rest-api

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Information on register_meta casting/coercing behavior

chrisvanpatten opened this issue · comments

Per discussion in core Slack, it would be helpful to clarify some of the behavior around type coercion in the API.

Here's a bit of text to kick off the process. Feel free to modify :)


Because the REST API's schema validation needs to work in different contexts (such as query strings, JSON, etc.), being explicit and consistent with your schema types is very important.

Consequently, you might find that values are not always coerced — that is, automatically transformed between types — in the way you are used to in PHP, with its inherent type flexibility.

For example, if you use register_meta to register a piece of array meta containing a string property, but then store the value as an integer, the REST API is not able to safely convert the integer to a string. In this case, the API would return null instead of your array.

To solve this, you can use a prepare_callback to cast the value to the expected type, before it's validated against your schema.

For example, to store and retrieve an array of string IDs—which may also be saved in your database as integers—you might use the following:

register_meta(
	'post',
	'my_id_array',
	[
		'type'         => 'array',
		'single'       => true,
		'show_in_rest' => [
			'schema' => [
				'items' => [
					'type' => 'string',
				],
			],
			'prepare_callback' => function ( $value ) {
				return array_map(
					function ( $item ) {
						return (string) $item;
					},
					$value
				);
			},
		],
	]
);

This will ensure that integers are correctly transformed so the data matches the registered schema before the data is returned in the API response.