The register_meta() WordPress PHP function registers a meta key for a specific combination of object type and object subtype.
Usage
register_meta( $object_type, $meta_key, $args );
Example:
register_meta( 'post', 'featured_color', array(
'type' => 'string',
'single' => true,
'sanitize_callback' => 'sanitize_text_field',
'auth_callback' => '__return_true'
));
Parameters
$object_type(string) – Required. Type of object metadata is for. Accepts ‘post’, ‘comment’, ‘term’, ‘user’, or any other object type with an associated meta table.$meta_key(string) – Required. Meta key to register.$args(array) – Required. Data used to describe the meta key when registered. Includes:object_subtype(string) – A subtype; e.g., if the object type is “post”, the post type. If left empty, the meta key will be registered on the entire object type. Default empty.type(string) – The type of data associated with this meta key. Valid values are ‘string’, ‘boolean’, ‘integer’, ‘number’, ‘array’, and ‘object’.single(bool) – Whether the meta key has one value per object or an array of values per object.sanitize_callback(callable) – A function or method to call when sanitizing$meta_keydata.auth_callback(callable) – Optional. A function or method to call when performing edit_post_meta, add_post_meta, and delete_post_meta capability checks.show_in_rest(bool|array) – Whether data associated with this meta key can be considered public and should be accessible via the REST API.
More information
See WordPress Developer Resources: register_meta()
Examples
Registering a simple string meta key for posts
This example registers a meta key called ‘featured_color’ for posts. The value is a single string sanitized using the sanitize_text_field function.
function my_register_post_meta() {
register_meta( 'post', 'featured_color', array(
'type' => 'string',
'single' => true,
'sanitize_callback' => 'sanitize_text_field',
'auth_callback' => '__return_true'
));
}
add_action( 'init', 'my_register_post_meta' );
Registering a boolean meta key for users
This example registers a meta key called ‘is_premium’ for users, which is a boolean value.
function my_register_user_meta() {
register_meta( 'user', 'is_premium', array(
'type' => 'boolean',
'single' => true,
'sanitize_callback' => 'rest_sanitize_boolean',
'auth_callback' => '__return_true'
));
}
add_action( 'init', 'my_register_user_meta' );
Registering an integer meta key for comments
This example registers a meta key called ‘rating’ for comments, which is an integer value.
function my_register_comment_meta() {
register_meta( 'comment', 'rating', array(
'type' => 'integer',
'single' => true,
'sanitize_callback' => 'absint',
'auth_callback' => '__return_true'
));
}
add_action( 'init', 'my_register_comment_meta' );