Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Information on register_meta casting/coercing behavior #59

Open
chrisvanpatten opened this issue Oct 25, 2019 · 0 comments
Open

Information on register_meta casting/coercing behavior #59

chrisvanpatten opened this issue Oct 25, 2019 · 0 comments

Comments

@chrisvanpatten
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant