Using WordPress ‘register_post_meta()’ PHP function

The register_post_meta() WordPress PHP function registers a meta key for posts.

Usage

register_post_meta( $post_type, $meta_key, $args )

Example:

register_post_meta( 'my_custom_post_type', 'custom_meta_key', array(
    'type' => 'string',
    'single' => true,
    'show_in_rest' => true,
));

Parameters

  • $post_type (string) – 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) – The meta key to register.
  • $args (array) – Data used to describe the meta key when registered. See register_meta() for a list of supported arguments.

More information

See WordPress Developer Resources: register_post_meta()

Examples

Registering a simple text meta key for a custom post type

This code registers a single text meta key for the custom post type ‘book’.

add_action( 'init', 'register_book_meta' );

function register_book_meta() {
    register_post_meta( 'book', 'author_name', array(
        'type' => 'string',
        'single' => true,
        'show_in_rest' => true,
    ));
}

Registering a meta key for all post types

This code registers a ‘rating’ meta key for all post types.

add_action( 'init', 'register_rating_meta' );

function register_rating_meta() {
    register_post_meta( '', 'rating', array(
        'type' => 'integer',
        'single' => true,
        'show_in_rest' => true,
    ));
}

Registering a meta key with a default value

This code registers a meta key with a default value of ‘0’.

add_action( 'init', 'register_views_meta' );

function register_views_meta() {
    register_post_meta( 'post', 'views', array(
        'type' => 'integer',
        'single' => true,
        'default' => 0,
        'show_in_rest' => true,
    ));
}

Registering a meta key with custom sanitization and authorization callbacks

This code registers a meta key with custom sanitization and authorization callbacks.

add_action( 'init', 'register_custom_meta' );

function register_custom_meta() {
    register_post_meta( 'post', 'custom_data', array(
        'type' => 'string',
        'single' => true,
        'sanitize_callback' => 'sanitize_text_field',
        'auth_callback' => 'my_auth_callback',
        'show_in_rest' => true,
    ));
}

function my_auth_callback( $allowed, $meta_key, $post_id, $user_id, $cap, $caps ) {
    return current_user_can( 'edit_post', $post_id );
}

Registering a meta key with an array type

This code registers a meta key with an array type for storing multiple values.

add_action( 'init', 'register_multivalue_meta' );

function register_multivalue_meta() {
    register_post_meta( 'post', 'tags', array(
        'type' => 'array',
        'single' => false,
        'show_in_rest' => true,
    ));
}