get_metadata()WP 2.9.0

Retrieve metadata for the specified object.

If the meta field exists, a single value is returned if $single is true, or an array of values if it's false.

If the meta field does not exist, the result depends on get_metadata_default(). By default, an empty string is returned if $single is true, or an empty array if it's false.

1 time — 0.00013 sec (fast) | 50000 times — 1.0 sec (very fast)

No Hooks.

Return

Mixed. An array of values if $single is false. The value of the meta field if $single is true. False for an invalid $object_id (non-numeric, zero, or negative value), or if $meta_type is not specified. An empty string if a valid but non-existing object ID is passed.

Usage

get_metadata( $meta_type, $object_id, $meta_key, $single );
$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)
Metadata key. If not specified, retrieve all metadata for the specified object.
Default: ''
$single(true|false)
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

Examples

0

#1 Retrieve Post metadata

A few examples that can be used to output post, user and comment metadata. I.e. these are alternatives to corresponding WP functions: get_post_meta(), get_user_meta(), get_comment_meta().

// get the custom field of post 17, directly in the variable
$post_meta = get_metadata( 'post', 17, 'robots', true );

// Get the user's nickname 14
$user_meta = get_metadata( 'user', 14, 'nickname', 1 );

// Get all the metadata of comment 115, as an array.
$comment_meta = get_metadata( 'comment', 115 );
0

#2 Example of returned array of all post metadatas

If we don't specify meta_key parameter, the function returns array of all meta-fields of post:

$metas = get_metadata( 'post', 115 );

// $metas will contain something like this:
array (
  '_pingme' => array (
	0 => '1',
  ),
  '_encloseme' => array (
	0 => '1',
  ),
  'custom key 1' => array (
	0 => 'custom value 1',
	1 => 'custom value 2',
  ),
  'custom key 2' => array (
	0 => 'custom value 3',
  ),
)

Notes

Changelog

Since 2.9.0 Introduced.

Code of get_metadata() WP 5.9.3

function get_metadata( $meta_type, $object_id, $meta_key = '', $single = false ) {
	$value = get_metadata_raw( $meta_type, $object_id, $meta_key, $single );
	if ( ! is_null( $value ) ) {
		return $value;
	}

	return get_metadata_default( $meta_type, $object_id, $meta_key, $single );
}