WordPress at Your Fingertips

get_post_meta()WP 1.5.0

Gets the value of the specified custom field of the post. Also can get an array of all post meta fields.

In order to obtain the values of all custom fields of a particular post, you need to leave empty the $key parameter. You can also use the get_post_custom() function to do this.

If the metadata contains a serialized array, it will be automatically processed by unserialize() function. So, to get unserialized data you do not need to use unserialize() function on received data.

1 time — 0.0007429 sec (slow) | 50000 times — 0.12 sec (very fast) | PHP 7.4.25, WP 6.0

No Hooks.

Return

Mixed.

  • Returns false when $post_id parameter passed wrongly.

  • If $single = true

    • string/array — when meta-field exists.
    • '' — when the meta-field not exists.
  • If $single = false
    • array of all metafield values — when metafield exists.
    • array() — when metafield not exists.

Note: If a number is stored in meta-field it will be returned as a string, for example, '54'...

Usage

get_post_meta( $post_id, $key, $single );
$post_id(int) (required)
Post ID whose custom field needs to be obtained.
$key(string)
The meta field name, the value you need to get. If leave the field empty, all post custom fields will be obtained.
Default: ''
$single(true/false)

Whether to return a single value.

true - return the single value of meta-field (if there are several values with this key, then only the first one will be returned).
false - return an array of all meta field values with the specified meta key.

If the value of a custom field contains a serialized array, then:
true returns a normal array.
false returns the array, first ([0]) element of which contains serialized array string.

Default: false

Examples

4

#1 You no longer need this function

Since WP 3.5, you can just call

$post->meta_key

it is the same as:

get_post_meta( $post->ID, 'meta_key', true )

This makes code a lot cleaner and more readable.

if( some_condiltion ) {
	$value = $post->_wp_page_template ?: 'not assigned';
}

If there are multiple values for the key “meta_key”, $post->meta_key will only return the first value. get_post_meta( $post_id, 'meta_key') will return all the values. Multiple values can be added using the add_post_meta() function.

0

#2 Check existence of a specified metafield

When you need to check whether a field exists (has any value: empty string or 0):

$metas = get_post_meta( $post->ID );
if( isset($metas['key_name']) ){
	echo 'The meta field "key_name" exists.';
}
0

#3 Other example of using custom fields functions

/**
 * This function handles the mood and listening_to meta tags.
 * It can be called with an action of update, delete, and get (default)
 * When called with an action of update, either $mood or $listening_to must be provided.
 * i.e. mood_music( $post->ID, 'update', 'Happy', 'Bon Jovi - It's My Life' );
 */
function mood_music( $post_id, $action = 'get', $mood = 0, $listening_to = 0 ){

	//Let's make a switch to handle the three cases of 'Action'
	switch( $action ){
		case 'update' :
			//If nothing is given to update, end here
			if( ! $mood && ! $listening_to ){
				return false;
			}

			//add_post_meta usage:
			//add_post_meta( $post_id, $meta_key, $meta_value, $unique = false )

			//If the $mood variable is supplied,
			//add a new key named 'mood', containing that value.
			//If the 'mood' key already exists on this post,
			//this command will simply add another one.
			if( $mood ){
				add_post_meta( $post_id, 'mood', $mood );

				return true;
			}

			//update_post_meta usage:
			//update_post_meta( $post_id, $meta_key, $meta_value )

			//If the $listening_to variable is supplied,
			//add a new key named 'listening_to', containing that value.
			//If the 'listening_to' key already exists on this post,
			//this command will update it to the new value
			if( $listening_to ){
				add_post_meta( $post_id, 'listening_to', $listening_to, true ) or
				update_post_meta( $post_id, 'listening_to', $listening_to );

				return true;
			}

			break;

		case 'delete' :
			//delete_post_meta usage:
			//delete_post_meta( $post_id, $meta_key, $prev_value = ' ' )

			//This will delete all instances of the following keys from the given post
			delete_post_meta( $post_id, 'mood' );
			delete_post_meta( $post_id, 'listening_to' );

			//To only delete 'mood' if it's value is 'sad':
			//delete_post_meta( $post_id, 'mood', 'sad' );
			break;

		case 'get' :
			//get_post_custom usage:
			//get_post_meta( $post_id, $meta_key, $single value = false )

			//$stored_moods will be an array containing all values of the meta key 'mood'
			$stored_moods = get_post_meta( $post_id, 'mood' );
			//$stored_listening_to will be the first value of the key 'listening_to'
			$stored_listening_to = get_post_meta( $post_id, 'listening_to', 'true' );

			//Now we need a nice ouput format, so that
			//the user can implement it how he/she wants:
			//ie. echo mood_music( $post->ID, 'get' );

			$return = '<div class="mood-music">';

			if( ! empty( $stored_moods ) ){
				$return .= '<strong>Current Mood</strong>: ';
			}

			foreach( $stored_moods as $mood ){
				$return .= $mood . ', ';
			}

			$return .= '<br/>';

			if( ! empty( $stored_listening_to ) ){
				$return .= '<strong>Currently Listening To</strong>: ';
				$return .= $stored_listening_to;
			}
			$return .= '</div>';

			return $return;

			break;
		default :
			return false;
	}

}
0

#4 Counting the number of all custom fields of all posts

This example shows how to print all unique custom fields in one query and calculate how many of them are used in the database. This query can be useful for the profiling of post custom fields:

global $wpdb;
$data = $wpdb->get_results("
	SELECT meta_key, count(*) as count FROM $wpdb->postmeta
	WHERE meta_key NOT LIKE '\_oembed%' GROUP BY meta_key
");

print_r( $data );

/*
Array (
	[0] => stdClass Object (
			[meta_key] => _edit_lock
			[count] => 2300
		)

	[1] => stdClass Object (
			[meta_key] => _edit_last
			[count] => 2123
		)
	...
)
*/
0

#5 Get an aGet an array of values of custom fields

Get the values of post 76 meta fields key_1; assumed that the post has several custom fields with this key:

$values = get_post_meta( 76, 'key_1' );
/*
Array
(
	[0] => value 1
	[1] => value 2
)
*/
0

#6 Get all custom fields of the post

If you do not specify a meta key, the function will return all meta fields of the post.

If the value is serialised, it will be retrieved as a string, i.e. you have to de-serialise it yourself:

$post_metas = get_post_meta( 76 );

/*
Array
(
	[_edit_lock] => Array
		(
			[0] => 1517175359:1
		)

	[_edit_last] => Array
		(
			[0] => 1
		)

	[views] => Array
		(
			[0] => 10164
		)

	[_thumbnail_id] => Array
		(
			[0] => 9556
		)

	[photo] => Array
		(
			[0] => https://example.com/wp-content/uploads/2010/03/Quicktags-API.png
			[1] => https://example.com/wp-content/uploads/2017/07/image.png
		)
	[serialized_value] => Array
		(
			[0] => a:2:{s:4:"name";s:6:"hexlet";s:4:"type";s:5:"admin";}
		)
)
*/

We can make it into string:

$post_metas = get_post_meta( 76 );
$post_metas = array_combine( array_keys( $post_metas ), array_column( $post_metas, '0' ) );

/*
Now output will be like here:

Array (
	[_edit_lock] => 1517175359:1
	[_edit_last] => 1
	[views] => 10164
	[_thumbnail_id] => 9556
	[photo] => https://example.com/wp-content/uploads/2010/03/Quicktags-API.png
)
*/
0

#7 Retrieve only one custom field

If there are several custom fields with the same key, to get only the first one (in a string), set $single to true:

$value = get_post_meta( 76, 'key_1', true ); //> value 1
0

#8 Join all metafields into an object

This example shows how you can combine all custom fields of a post, to then use them in convenient way.

You may need it when you supposed to use a lot of different post custom fields in one code. It is not convenient to get each value with this function, but it is more convenient to get all the fields once, create an object from them and then take the data from the object - this works faster, and your code become clearer.

It is assumed that the keys of custom fields are in latin and the field with one key has only one value:

// collect meta to object
$meta = new stdClass;
foreach( (array) get_post_meta( $post->ID ) as $k => $v )
	$meta->$k = $v[0];

// Now, let's say the post has metafield 'book'
// Get it like so:
echo $meta->book;

Also, you can get the value of postmeta directly from WP_Post object: $post->my_meta_key. $post here is a WP_Post object and my_meta_key the name of metafield which value you want to get.

0

#9 Checking that the meta-field exists

Return values when no meta field is found
If a meta field with the given $key isn’t found for the given $post_id, the return value varies:

If $single = true, an empty string is returned.
If $single = false, an empty array is returned.

Since both evaluate as false, you can use get_post_meta directly in conditionals, like this:

$value = get_post_meta( 76, 'key_1', true ); // single

if( $value ){
	// the meta-field exists
}

$value = get_post_meta( 76, 'key_1' ); // multiple

if( $value ){
	// the meta-field exists
}

This code the same as:

$value = get_post_meta( 76, 'key_1', true );

if( '' !== $value ){
	// the meta-field is
}

$value = get_post_meta( 76, 'key_1' );

if( [] !== $value ){
	// the meta-field is
}
What if I want to store an empty string?

If for some reason your with to store an empty string or array into your meta field, get_post_meta() will not be reliable when checking if the given meta field exists.

In this case, you can use get_post_custom_keys() to do so:

$post_id = 1;
$meta_exists = in_array( 'key_1', get_post_custom_keys( $post_id ), true );

if( $meta_exists ) {
	// this correctly checks for the existence of the given key, 
	// even if it's empty or has a value that evaluates as false. 
} 
0

#10 Default Usage

Get the meta for all keys for the current post:

$meta = get_post_meta( $post_id );

Get all meta for a single key for the current post:

$key_1_values = get_post_meta( $post_id, 'key_1' );

Get the first value of a meta key for the current post:

$key_1_value = get_post_meta( $post_id, 'key_1', true );
0

#11 Don’t specify a $key and set $single = true

In this case function will return all keys still with an array of values.

$meta = get_post_meta( $post_id, '', true );
print_r( $meta );

/*
Array ( 
	[key_1] => Array ( [0] => value_1 ), 
	[key_2] => Array ( [0] => value_2 ) 
)
*/
-1

#12 Example of using this function inside the Loop.

The example below shows how to use this function to get the value of thumb custom field. The value contains a link to a thumbnail image.

<?php 
$thumb = get_post_meta( $post->ID, 'thumb', true );

if ( $thumb ) {
	?>
	<a href="<?php the_permalink() ?>" rel="bookmark">
		<img class="thumb" src="<?php echo $thumb ?>" alt="<?php the_title(); ?>" />
	</a>
	<?php
}
?>

Changelog

Since 1.5.0 Introduced.

get_post_meta() code WP 6.5.2

function get_post_meta( $post_id, $key = '', $single = false ) {
	return get_metadata( 'post', $post_id, $key, $single );
}
1 comment
    Log In