register_post_meta( string $post_type, string $meta_key, array $args ): bool

Registers a meta key for posts.

Parameters

$post_typestringrequired
Post type to register a meta key for. Pass an empty string to register the meta key across all existing post types.
$meta_keystringrequired
The meta key to register.
$argsarrayrequired
Data used to describe the meta key when registered. See register_meta() for a list of supported arguments.

Return

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

Source

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

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

Changelog

VersionDescription
4.9.8Introduced.

User Contributed Notes

  1. Skip to note 4 content

    If you are wondering why it doesn’t work for your custom post type when doing a block editor plugin or something,
    Your custom post type needs to support custom-fields.

        register_post_type( 'book', array(
        	...
        	'supports' => array( 'title', 'editor', 'custom-fields', ..., ),
        	// Make sure you add custom-fields here ^^^^^^^^^^^^^
        	...
        ) );
  2. Skip to note 6 content

    A default registered for all post types shadows the per-post-type one

    Passing an empty string as $post_type stores the key under an empty object subtype. For most arguments that behaves like the fallback the parameter description suggests, but for default it does not — the wildcard entry wins outright.

    filter_default_metadata() gathers every registered default for the key and then short-circuits on the empty subtype before the post type is ever resolved:

    register_post_meta( '', 'wpdocs_color', array(
    	'type'    => 'string',
    	'single'  => true,
    	'default' => 'red',
    ) );
    
    register_post_meta( 'book', 'wpdocs_color', array(
    	'type'    => 'string',
    	'single'  => true,
    	'default' => 'blue',
    ) );
    
    get_post_meta( $book_id, 'wpdocs_color', true ); // 'red', not 'blue'

    Registration order makes no difference and nothing is logged.

    The REST API resolves the same pair the other way around: registered fields are assembled by merging the keys registered for the whole object type first and the subtype-specific keys second, so there the post type wins. One meta key can therefore report blue through the REST API and the block editor while get_post_meta() returns red in PHP.

    This is worth ruling out whenever a registered default disagrees with what the editor shows, since the conflicting registration usually comes from another plugin. Note that get_registered_meta_keys( ‘post’, ‘book’ ) will not reveal it — that function returns only the exact subtype bucket, never the wildcard one.

You must log in before being able to contribute a note or feedback.