register_post_meta()WP 4.9.8

Registers a meta key for posts (post custom field).

It is a wrapper for the register_meta function for easy registration of post meta-fields.

To do the same for taxonomy, see register_term_meta().

The registered meta fields are stored in the global $wp_meta_keys array.

1 time — 0.000126 sec (fast) | 50000 times — 0.27 sec (very fast) | PHP 7.1.11, WP 4.9.8

No Hooks.

Return

true|false. True if the meta key was successfully registered, false if not.

Usage

register_post_meta( $post_type, $meta_key, $args );
$post_type(string) (required)
Post type to register a meta key for. Pass an empty string to register the meta key across all existing post types.
$meta_key(string) (required)
The meta key to register.
$args(array) (required)
Data used to describe the meta key when registered. See register_meta() for a list of supported arguments.

Examples

0

#1 Register a meta-field for pages only

register_post_meta( 'page', 'my_meta_key', [
	// Add to the REST response
	'show_in_rest' => true, 
	// Process the value of the field when saving it to the database, absint()
	'sanitize_callback' => 'absint', 
] );

Now the meta-field with the key 'my_meta_key' will be registered only for pages.

You can do the same with register_meta(), like this:

register_meta( 'post', 'my_meta_key', [
	'object_subtype'    => 'page', // post type
	'show_in_rest'      => true,
	'sanitize_callback' => 'absint',
] );
0

#2 Another example

See the register_meta() function page for more examples and nuances of use.

0

#3 Gutenberg editor note

For the meta-fields registered in this way to work in the block editor, you need to have a value of custom-fields in the supports field when registering the post type:

register_post_type( 'book', [
	...
	'supports' => [ 'title', 'editor', 'custom-fields', ... ],
	...
] );

Changelog

Since 4.9.8 Introduced.

register_post_meta() code WP 6.6.2

function register_post_meta( $post_type, $meta_key, array $args ) {
	$args['object_subtype'] = $post_type;

	return register_meta( 'post', $meta_key, $args );
}