Using WordPress ‘get_metadata()’ PHP function

The get_metadata() WordPress PHP function retrieves the value of a metadata field for the specified object type and ID.

Usage

get_metadata($meta_type, $object_id, $meta_key = '', $single = false);

Parameters

  • $meta_type (string) – Required. Type of object metadata is for. Accepts ‘post’, ‘comment’, ‘term’, ‘user’, or any other object type with an associated meta table.
  • $object_id (int) – Required. ID of the object metadata is for.
  • $meta_key (string) – Optional. Metadata key. If not specified, retrieve all metadata for the specified object. Default: ”.
  • $single (bool) – Optional. If true, return only the first value of the specified $meta_key. This parameter has no effect if $meta_key is not specified. Default: false.

More information

See WordPress Developer Resources: get_metadata

Examples

Get all metadata for a post

// Get all metadata for a post with ID 123
$all_metadata = get_metadata('post', 123);

Get a specific metadata value for a post

// Get the value of 'my_custom_key' for a post with ID 123
$meta_value = get_metadata('post', 123, 'my_custom_key', true);

Get all values of a specific metadata key for a user

// Get all values of 'my_custom_key' for a user with ID 456
$meta_values = get_metadata('user', 456, 'my_custom_key');

Get all metadata for a term

// Get all metadata for a term with ID 789
$term_metadata = get_metadata('term', 789);

Get a specific metadata value for a comment

// Get the value of 'comment_rating' for a comment with ID 111
$comment_rating = get_metadata('comment', 111, 'comment_rating', true);