WordPress at a glance

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.

Works based on: get_metadata()
✈ 1 time = 0.001012s = very slow | 50000 times = 0.09s = speed of light | PHP 7.2.5, WP 5.0.1

No Hooks.

Return

String/array.

  • Returns false when $post_id parameter passed wrongly.

  • If $single = true

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

If a number is stored in metafield value 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 name of meta field, the value of which 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

#1. Get 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
)
*/

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

$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
		)

)
*/

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

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

#4. 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 if ( $thumb = get_post_meta( $post->ID, 'thumb', true ) ) : ?>
	<a href="<?php the_permalink() ?>" rel="bookmark">
		<img class="thumb" src="<?php echo $thumb ?>" alt="<?php the_title(); ?>" />
	</a>
<?php endif; ?>

#5. 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.';
}

#6. 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;
	}

}

#7. Output 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
		)
	...
)
*/

Code of get post meta: wp-includes/post.php WP 5.2.1

<?php
function get_post_meta( $post_id, $key = '', $single = false ) {
	return get_metadata( 'post', $post_id, $key, $single );
}

Related Functions

From tag: Metadatas (any)

No comments
    Hello, !     Log In . Register