mixed An array of values if $single is false.
The value of the meta field if $single is true.
False for an invalid $post_id (non-numeric, zero, or negative value).
An empty array if a valid but non-existing post ID is passed and $single is false.
An empty string if a valid but non-existing post ID is passed and $single is true.
Please note that if a db collation is case insensitive (has with suffix _ci) then update_post_meta and delete_post_meta and get_posts() will update/delete/query the meta records with keys that are upper or lower case. However get_post_meta will apparently be case sensitive due to WordPress caching. See https://core.trac.wordpress.org/ticket/18210 for more info. Be careful not to mix upper and lowercase.
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 is true, an empty string is returned.
If $single is false, an empty array is returned.
Since both evaluate as false, you can use get_post_meta directly in conditionals, like this:
if( ! get_post_meta( '1', 'non-existing_meta', true ) ) {}
if( ! get_post_meta( '1', 'non-existing_meta', false ) ) {}
// both ifs will get run if no meta field is found; since
// array() == false and '' == false
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:
if( ! in_array( 'given_key', get_post_custom_keys( '1' ) ) ) {}
// this correctly checks for the existence of the given key,
// even if it's empty or has a value that evaluates as false.
“If $single is true, an empty string is returned. If $single is false, an empty array is returned.” This is not true anymore. For WordPress 5.2.2: If $single is true: if the meta value is scalar, null is returned; otherwise, an empty array is returned. If $single is false: if the meta value is scalar, an array containing one null element is returned; otherwise, an array containing one empty array is returned. Therefore, one can’t check if the key exists or not, in the case the meta value is an array, because it will return an empty array, whether the value is set or not.
The best thing about this function is that you no longer need to use it :)
Since r21559 (v3.5), you can just call $post->foo to fetch the equivalent of get_post_meta( $post->ID, 'foo', true ).
You can even extend that to introduce dynamically-generated fields, so you can call echo esc_html( $post->bar ) instead of $bar = some_custom_logic( get_post_meta( $post->ID, 'bar', true ) ); echo esc_html( $bar ).
This makes code a lot cleaner and more readable.
add_filter( 'get_post_metadata', 'add_dynamic_post_meta', 10, 4 );
/**
* Add dynamically-generated "post meta" to `\WP_Post` objects
*
* This makes it possible to access dynamic data related to a post object by simply referencing `$post->foo`.
* That keeps the calling code much cleaner than if it were to have to do something like
* `$foo = some_custom_logic( get_post_meta( $post->ID, 'bar', true ) ); echo esc_html( $foo )`.
*
* @param mixed $value
* @param int $post_id
* @param string $meta_key
* @param int $single @todo handle the case where this is false
*
* @return mixed
* `null` to instruct `get_metadata()` to pull the value from the database
* Any non-null value will be returned as if it were pulled from the database
*/
function add_dynamic_post_meta( $value, $post_id, $meta_key, $single ) {
$post = get_post( $post_id );
if ( 'page' != $post->post_type ) {
return $value;
}
switch ( $meta_key ) {
case 'verbose_page_template':
$value = "The page template is " . ( $post->_wp_page_template ?: 'not assigned' );
break;
}
return $value;
}
If there are multiple values for the key “bar”, $post->bar will only return the first value. get_post_meta( get_the_ID(), 'bar') will return all the values for the key “bar”. Multiple values can be added to a key using the add_post_meta function. Values can be removed with delete_post_meta.
I don’t think this is good advice. First, any classic Post Meta key (using dashes) will produce a fatal error. At least it’d have to be `$post->{‘my-post-meta’}`. Second, any post meta storing an array of data, will fail and return only the first item of the array, afaik. So, get_post_meta _is_ still the right thing to use when getting post meta, since post meta is _not_ post data, but… post meta.
Show the first value of the specified key inside a loop
$key_1_value = get_post_meta( get_the_ID(), 'key_1', true );
// Check if the custom field has a value.
if ( ! empty( $key_1_value ) ) {
echo $key_1_value;
}
Retrieve a Custom Field Thumbnail Url
While you are in the WordPress Loop, you can use this code to retrieve a custom field. In this example, the thumbnail image url is in a custom field named “thumb”.
If the value of the $key parameter is falsy get_post_meta will return the entire post meta array, even if $single is set to true. for example:
get_post_meta( $post_id, FALSE, TRUE); //Returns all the post meta fields as an array.
get_post_meta( $post_id, '0', TRUE); //Will also return all the post meta fields as an array.
register_post_meta() allows you to define a default value for a meta field. If the default value evaluates to true, you’ll be scratching your head why get_post_meta() returns true when you haven’t yet set a value, or just used delete_post_meta() .
Just for the record, WordPress returns either empty string (”) or an empty array (is_countable and count === 0) when you attempt to retrieve a meta value using a post ID or meta key that doesn’t exist.
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 is true, an empty string is returned.
If $single is false, an empty array is returned.
Since both evaluate as false, you can use get_post_meta directly in conditionals, like this:
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:
The best thing about this function is that you no longer need to use it :)
Since r21559 (v3.5), you can just call
$post->foo
to fetch the equivalent ofget_post_meta( $post->ID, 'foo', true )
.You can even extend that to introduce dynamically-generated fields, so you can call
echo esc_html( $post->bar )
instead of$bar = some_custom_logic( get_post_meta( $post->ID, 'bar', true ) ); echo esc_html( $bar )
.This makes code a lot cleaner and more readable.
$post->bar
will only return the first value.get_post_meta( get_the_ID(), 'bar')
will return all the values for the key “bar”. Multiple values can be added to a key using theadd_post_meta
function. Values can be removed withdelete_post_meta
.Show the first value of the specified key inside a loop
Default Usage
Get the meta for all keys for the current post:
Get all meta for a single key for the current post:
Get the first value of a meta key for the current post:
Retrieve a Custom Field Thumbnail Url
While you are in the WordPress Loop, you can use this code to retrieve a custom field. In this example, the thumbnail image url is in a custom field named “thumb”.
When you don’t specify a $key (”) and set $single to true in get_post_meta, it will return all keys still with an array of values.
If you want to hide postmeta keys from the customfields prefix the key name with an underscore.
When we calling for all post meta, it will returned array value:
sample output:
We can make it into string, array_column will resulting default array value into string, for sure we need array combine to re-form array key:
now output will be like here:
Display single meta value using meta key
Post meta keys are case-sensitive
If the value of the
$key
parameter is falsyget_post_meta
will return the entire post meta array, even if$single
is set totrue
. for example:Function The Retrieve a Number views in post
Note that to add or set post meta values you can use the function
add_post_meta
:Here’s a pitfall to steer clear of…
register_post_meta() allows you to define a default value for a meta field. If the default value evaluates to true, you’ll be scratching your head why get_post_meta() returns true when you haven’t yet set a value, or just used delete_post_meta() .
Obviously get_post_meta() will return the default value defined in register_post_meta() .
False if post ID isn’t absint or is 0
Passing
$post_id == 0
(or anything not a absint) will return false no matter$single
.