Currently Available: Need a skilled Software Developer for your next project?
Categories
WordPress

How to Add Custom Post Meta to WordPress REST API Responses

WordPress does not automatically return extra information stored with a post in a REST API response. This information is post metadata, often called post meta. Examples include a subtitle or an external reference code. You can make a metadata key available by registering the meta with show_in_rest, or add a separate response field with register_rest_field.

Use register_post_meta() to expose and manage a registered metadata key inside the response’s meta object. Use register_rest_field() to add a field at the top level of the response or calculate its value. Both methods need registration code. Set the field’s type and access rules to match its data.

Expose a registered meta key under meta

To include a standard metadata field in a post response, register its key with register_post_meta() and set show_in_rest to true. WordPress then returns the key inside meta. The WordPress REST response guidance describes this approach.

Add registration code to a plugin or your theme’s functions.php file:

add_action( 'init', function () {
    register_post_meta(
        'post',
        'subtitle',
        array(
            'type'              => 'string',
            'single'            => true,
            'show_in_rest'      => true,
            'sanitize_callback' => 'sanitize_text_field',
            'auth_callback'     => function ( $allowed, $meta_key, $post_id ) {
                return current_user_can( 'edit_post', $post_id );
            },
        )
    );
} );

Here, post names the post type and subtitle is the metadata key. single => true tells WordPress to return one value for that key on each post. The sanitizer cleans text that someone submits. The authorization callback allows a user to edit the value only if they can edit that post.

For a custom post type, register the meta under that type’s name. When you register the post type, enable REST access and support for custom fields by setting show_in_rest => true and adding custom-fields support. Without these settings, the post type or its registered metadata will not be available through the expected REST API route.

After registration, the post response includes the value inside meta, alongside the other post data. The REST API also accepts updates to registered metadata when the submitted value matches the field’s schema and the user has permission. If the endpoint returns no value, check that the metadata key matches the key stored on the post and that the post type is registered for REST access.

Add a top-level field with register_rest_field()

Use register_rest_field() to put a field such as subtitle beside title and content in the response, instead of inside meta. Use it also when you calculate a value from one or more metadata keys. As WordPress prepares each post response, it runs the supplied get_callback function. The function receives the post data, including its ID, and can use that ID to retrieve the metadata value.

add_action( 'rest_api_init', function () {
    register_rest_field(
        'post',
        'subtitle',
        array(
            'get_callback' => function ( $object ) {
                return get_post_meta( $object['id'], 'subtitle', true );
            },
            'schema'       => array(
                'description' => 'Subtitle for the post.',
                'type'        => 'string',
                'context'     => array( 'view', 'edit' ),
            ),
        )
    );
} );

Register the field on rest_api_init so WordPress adds it when the REST API starts. The field schema tells WordPress the value’s type and which contexts, such as viewing or editing, allow clients to request it. The register_rest_field example shows this pattern for adding fields to REST responses.

This example only reads data. To let clients update the field through the REST API, add an update_callback function that checks and saves the submitted value. Without that function, the custom field is read-only. Keep permission checks and sanitization for any value clients can change.

Check the response and choose the right route

Request a post from its REST endpoint and inspect the JSON response. If you used register_post_meta(), look for the key inside meta. If you used register_rest_field(), look for the field at the top level. If the field is missing, check that the registration runs on the right hook and uses the correct post type and field name.

A field registered with register_rest_field() appears in responses that WordPress prepares with its standard post controller, the code that builds those responses. A custom route that returns a WP_Post object directly skips that controller’s registered-field handling. For that route, extend the controller that handles it or add the field to the response yourself, as described in this custom-route discussion.

Give custom data a new field name. Do not change or remove standard response fields that existing clients may rely on. WordPress’s response-extension guidance recommends preserving existing fields. Keep private values out of public REST responses. Registration makes data available to API clients based on its context and access rules.

What I'm building

Delegate tasks. Get software.

Give Vroni a GitHub issue, bug report, spec, or rough idea. It reads the repo, plans the change, writes code, runs checks, and works toward a review-ready pull request.

Take a look at vroni.com

Email updates

Usually a new article and a few links I found interesting.

No spam. Unsubscribe with one click.

Leave a Reply

Your email address will not be published. Required fields are marked *