Using WordPress ‘register_rest_field()’ PHP function

The register_rest_field() WordPress PHP function registers a new field on an existing WordPress object type, such as “post”, “term”, or “comment”.

Usage

register_rest_field( $object_type, $attribute, $args );

Parameters

  • $object_type (string|array) – Required. Object(s) the field is being registered to, “post”, “term”, “comment”, etc.
  • $attribute (string) – Required. The attribute name.
  • $args (array) – Optional. An array of arguments used to handle the registered field, which includes:
    • get_callback (callable|null) – Optional. The callback function used to retrieve the field value. Default is ‘null’, the field will not be returned in the response.
    • update_callback (callable|null) – Optional. The callback function used to set and update the field value. Default is ‘null’, the value cannot be set or updated.
    • schema (array|null) – Optional. The schema for this field. Default is ‘null’, no schema entry will be returned.

More information

See WordPress Developer Resources: register_rest_field()

Examples

Register a field to a post

This code snippet registers a field called ‘my_field’ to a post object:

add_action( 'rest_api_init', function () {
    $field = 'my_field';
    register_rest_field( 'post', $field, array(
        'get_callback' => function ( $object ) use ( $field ) {
            return get_post_meta( $object['id'], $field, true );
        },
        'update_callback' => function ( $value, $object ) use ( $field ) {
            update_post_meta( $object->ID, $field, $value );
        },
        'schema' => array(
            'type' => 'string',
            'arg_options' => array(
                'sanitize_callback' => function ( $value ) {
                    return sanitize_text_field( $value );
                },
                'validate_callback' => function ( $value ) {
                    return (bool) preg_match( '/\\A[a-z]{10}\\Z/', $value );
                },
            ),
        ),
    ) );
} );

Register a field to a term

This code snippet registers a field called ‘my_term_field’ to a term object:

add_action( 'rest_api_init', function () {
    $field = 'my_term_field';
    register_rest_field( 'term', $field, array(
        'get_callback' => function ( $object ) use ( $field ) {
            return get_term_meta( $object['id'], $field, true );
        },
        'update_callback' => function ( $value, $object ) use ( $field ) {
            update_term_meta( $object->term_id, $field, $value );
        },
        'schema' => array(
            'type' => 'string',
        ),
    ) );
} );