Using WordPress ‘add_metadata()’ PHP function

The add_metadata() WordPress PHP function adds metadata for a specific object. The object can be of type ‘post’, ‘comment’, ‘term’, ‘user’, or any other type with an associated meta table.

Usage

add_metadata( $meta_type, $object_id, $meta_key, $meta_value, $unique );

For instance, if you want to add a custom metadata ‘color’ to a post with ID 123 and set its value to ‘blue’, you would do this:

add_metadata( 'post', 123, 'color', 'blue', true );

Parameters

  • $meta_type (string) – The type of object the metadata is for. This accepts ‘post’, ‘comment’, ‘term’, ‘user’, or any other object type with a related meta table.
  • $object_id (int) – The ID of the object the metadata is for.
  • $meta_key (string) – The metadata key.
  • $meta_value (mixed) – The metadata value. This must be serializable if it’s non-scalar.
  • $unique (bool) – This is optional. If set to true, the metadata key will be unique for the object. If the object already has a value for the specified metadata key, no change will be made. Default is false.

More information

See WordPress Developer Resources: add_metadata()

This function was implemented in WordPress 2.9.0.

Examples

Add Metadata to a Post

// This code adds a 'color' metadata to post with ID 123
add_metadata( 'post', 123, 'color', 'blue', true );

Add Metadata to a User

// This code adds a 'hobby' metadata to a user with ID 55
add_metadata( 'user', 55, 'hobby', 'golf', false );

Add Metadata to a Term

// This code adds 'description' metadata to a term with ID 77
add_metadata( 'term', 77, 'description', 'This is a term description', true );

Add Metadata to a Comment

// This code adds 'location' metadata to a comment with ID 88
add_metadata( 'comment', 88, 'location', 'Australia', true );

Update Metadata If Not Unique

// This code attempts to add 'color' metadata to post with ID 123, but since it's not unique, no change will be made
add_metadata( 'post', 123, 'color', 'green', true );