register_rest_field()WP 4.7.0

Registers a new REST field for the specified type of REST object (resource).

The function should be called on the rest_api_init event. Using this event instead of init will prevent the field from being registered during requests to WordPress that do not use the REST API.

How the function works

In the REST API, a global variable $wp_rest_additional_fields is used. It contains all the response fields that are output for a specific object (resource). The REST API uses the function register_rest_field() as a helper to add a field to this global variable. Working with this global variable directly is not recommended for backward compatibility reasons.

For each REST resource (posts, terms, comments, users, etc.), the variable $wp_rest_additional_fields contains an array with the names of the fields and callback functions for retrieving or updating the values of these fields.

1 time — 0.000001 sec (speed of light) | 50000 times — 0.04 sec (speed of light) | PHP 7.1.11, WP 4.9.8

No Hooks.

Returns

null. Nothing (null)

Usage

register_rest_field( $object_type, $attribute, $args );
$object_type(string/array) (required)

The name of the REST resource for which the field is registered. Multiple resources can be specified in an array.

Here you need to specify what ultimately appears in the title field from the array returned by the controller method get_item_schema() of the current REST resource. For example, for users, you need to specify user - see what is in the title in the code of the method WP_REST_Users_Controller::get_item_schema().

Possible values:

  • Terms: taxonomy label. For example category, custom_taxonomy. For tags, the exception: you need to specify tag, not post_tag - see WP_REST_Terms_Controller::get_item_schema().
  • Posts: post type label. For example: post, page, custom_post_type.
  • Users: user.
  • Comments: comment.
$attribute(string) (required)
The name of the field. This field will be used as a key in the REST response object.
$args(array)

Parameters for processing the specified field during the REST request.

  • get_callback(string/array/null)
    PHP Function for retrieving the value of the field.

    The callback function accepts the following parameters:

    • $prepared – (array) Prepared request data. For example, the data of the WP_Post object in array form.
    • $field_name – (string) The name of the field specified in the second parameter of the register_rest_field() function.
    • $request – (object) All request data as a WP_REST_Request object.
    • $object_type – (string) The type of object for which the field was registered. Usually, this is the value of the first parameter of the register_rest_field() function.

    Default: null - the value will not be shown in the response

  • update_callback(string/array/null)
    PHP Function used to set and update the value of the field.

    The callback function accepts the following parameters:

    • $value – The value of the POST request for the current field.
    • $post – (object) The request object - $request[ $field_name ]. For example, WP_Post.
    • $field_name – (string) The name of the field specified in the second parameter of the register_rest_field() function.
    • $request – (object) All request data as a WP_REST_Request object.
    • $object_type – (string) The type of object for which the field was registered. Usually, this is the value of the first parameter of the register_rest_field() function.

    Default: null - the value cannot be set or updated

  • schema(string/array/null)
    Array describing the schema of this field.
    Default: null - the schema will not be shown

Default: array()

Examples

0

#1 Create a field that displays the name of the author of the post

add_action( 'rest_api_init', function(){

	register_rest_field( 'post', 'my_awesome_field', array(
		'get_callback' => function( $post, $field_name, $request ){
			return get_the_author_meta( 'display_name', $post['author'] );
		},
		'update_callback' => null,
		'schema' => [
			'description' => __( 'User public name', 'my_domain' ), 
			'type' => 'string'
		],
	) );

} );

Now, the field my_awesome_field can be found in the JSON response of the http://example.com/wp-json/wp/v2/posts route.

0

#2 Get custom posts by custom field. Or update the custom field of a custom post

To make use of sanitize_callback and validate_callback, pass those in arg_options in schema.

add_action( 'rest_api_init', 'slug_register_my_post_types' );

function slug_register_my_post_types() {

	register_rest_field( 'my_post_type', 'my_custom_field',
		[
			'get_callback'    => function( $object, $field_name, $request ) {
				return get_post_meta( $object['id'], $field_name );
			},
			'update_callback' => function( $value, $object, $field_name ) {
				return update_post_meta( $object->ID, $field_name, strip_tags( $value ) );
			},
			'schema'          => [
				'type'        => 'string',
				'arg_options' => [
					'sanitize_callback' => function( $value ) {
						// Make the value safe for storage.
						return sanitize_text_field( $value );
					},
					'validate_callback' => function( $value ) {
						// Valid if it contains exactly 10 English letters.
						return (bool) preg_match( '/\A[a-z]{10}\Z/', $value );
					},
				],
			],
		]
	);
}

With this GET request, you can get a list of posts sorted by the value of the my_custom_field meta-field:

GET https://myexample.com/wp-json/wp/v2/my_post_type?filter[meta_query][0][key]=my_custom_field&filter[meta_query][0][value]=my_find_value

And you can update the value of this meta field with a POST request

POST https://myexample.com/wp-json/wp/v2/my_post_type/{id}

where {id} is the id of the desired post and the query parameters specify: my_custom_field => 'new_value'.

0

#3 Add the featured_image_url field to the post response data

Useful for showing the main image in gutenberg block development when posts are fetched with withSelect() function..

add_action( 'rest_api_init', function () {

	register_rest_field( 'post', 'featured_image_url', array(
		'get_callback' => function ( $post_arr ) {
			$image_data = wp_get_attachment_image_src( $post_arr['featured_media'], 'medium' );

			return $image_data[0];
		},
		'update_callback' => null,
		'schema' => null
	) );
} );
0

#4 Parameters passed to callback functions

For get_callback:

  • $post – (object) Request object, for example WP_Post.
  • $attribute – (string) The field name specified in the second parameter of register_rest_field().
  • $request – (object) All request data in the form of a WP_REST_Request object.
  • $object_type – (string) The object type for which the field was registered. This is usually the value of the first register_rest_field() parameter.

For update_callback:

  • $value – The POST request value for the current field.
  • $post – (object) Request object, for example WP_Post.
  • $attribute – (string) The field name specified in the second parameter of register_rest_field().
  • $request – (object) All request data in the form of a WP_REST_Request object.
  • $object_type – (string) The object type for which the field was registered. This is usually the value of the first register_rest_field() parameter.

Notes

  • Global. Array. $wp_rest_additional_fields Holds registered fields, organized by object type.

Changelog

Since 4.7.0 Introduced.

register_rest_field() code WP 6.9.1

function register_rest_field( $object_type, $attribute, $args = array() ) {
	global $wp_rest_additional_fields;

	$defaults = array(
		'get_callback'    => null,
		'update_callback' => null,
		'schema'          => null,
	);

	$args = wp_parse_args( $args, $defaults );

	$object_types = (array) $object_type;

	foreach ( $object_types as $object_type ) {
		$wp_rest_additional_fields[ $object_type ][ $attribute ] = $args;
	}
}