REST API & Developer PHP Intermediate

Make a Custom Field Available in the REST API

Register a post meta field so it can be read and saved through the REST API and used by block editor sidebars.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 13 lines
add_action( 'init', function (): void {
	register_post_meta( 'post', 'nahnu_subtitle', [
		'type'              => 'string',
		'description'       => 'A short subtitle shown under the post title.',
		'single'            => true,
		'default'           => '',
		'show_in_rest'      => true,
		'sanitize_callback' => 'sanitize_text_field',
		'auth_callback'     => function ( $allowed, string $meta_key, int $post_id ): bool {
			return current_user_can( 'edit_post', $post_id );
		},
	] );
} );

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.

Custom fields are hidden from the REST API unless you register them. Registering a field properly also tells WordPress its type, how to clean it and who may change it, which the block editor needs if you want to edit the field in a sidebar panel.

How it works

register_post_meta() describes one meta key for a post type. 'show_in_rest' => true adds it to the meta object in REST responses and lets authorised users update it there.

The sanitize_callback cleans every value before it’s saved, and the auth_callback only allows people who can edit the post to change it.

Things to watch

  • Meta keys starting with an underscore are “protected” and need auth_callback to be editable at all.
  • For arrays or objects, set 'type' => 'array' or 'object' and give show_in_rest a schema.
  • Your post type must support custom-fields for meta to appear in its REST responses.

How to test it

Request /wp-json/wp/v2/posts/1?context=edit while logged in. You should see "meta": { "nahnu_subtitle": "" }.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only