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.0005281 sec (slow) | 50000 times — 0.14 sec (very fast) | PHP 7.4.25, WP 6.0

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 array if a valid but non-existing object ID is passed and $single is false. An empty string if a valid but non-existing object ID is passed and $single is true.

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: empty string
$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

1

#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 );
-19

#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.

get_metadata() code WP 6.7.1

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 );
}