Function and usage of register_post_meta() in wordpress


Answers ( 1 )


    The register_post_meta() function in WordPress is used to register a meta key for posts. This function allows developers to store additional information (metadata) about posts in WordPress.

    Function Syntax

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


    1. $post_type (string, required): The post type for which the meta key is being registered. If you pass an empty string (''), the meta key will be registered for all existing post types.

    2. $meta_key (string, required): The meta key that is being registered.

    3. $args (array, required): An array of arguments that describe the meta key. These are similar to the arguments used in register_meta(). The key elements of $args include:

      • object_subtype (string): A subtype, like the specific post type if the object type is "post". If left empty, the meta key will be registered for the entire object type. Default is empty.
      • type (string): Defines the type of data associated with this meta key. Valid values include 'string', 'boolean', 'integer', 'number', 'array', and 'object'.
      • description (string): A description of the data attached to this meta key.
      • single (bool): Determines whether the meta key has a single value per object (true) or an array of values per object (false).
      • default (mixed): The default value returned from get_metadata() if no value is set. For non-single meta keys, this default value is the first entry in an array.
      • sanitize_callback (callable): A function or method called when sanitizing the meta key data.
      • auth_callback (callable, optional): A function or method for capability checks when editing, adding, or deleting the meta key.
      • show_in_rest (bool|array): Whether the meta key data is public and accessible via the REST API. For complex meta values, this can be an array with 'schema' or 'prepare_callback' keys instead of a boolean.
      • revisions_enabled (bool): Enables revision support for the meta key. Only applicable when the object type is 'post'.

    Return Value

    The function returns bool:

    • true if the meta key was successfully registered.
    • false if the registration failed.

    Example Usage

    add_action( 'init', 'register_my_meta' );
    function register_my_meta() {
        register_post_meta( 'my_custom_post_type', 'my_meta_key', array(
            'type' => 'string',
            'single' => true,
            'show_in_rest' => true,

    In this example, register_my_meta() is hooked to WordPress's init action. It registers a meta key 'my_meta_key' for a custom post type 'my_custom_post_type'. The meta key is of type string, is single (not an array), and is shown in WordPress REST API responses.

Leave an answer