When the last parameter for get_post_meta()
is TRUE
, WordPress will return a single value: the newestlast entry in the post meta value for the given key.
The first call to get_post_meta()
will fetch all meta values for that post ID, so later calls will not result in additional database queries.
An example
Let’s say, we create a post meta key named color
and fill it with three different values for one post. Then we do the same with a key age
.
add_action( 'wp_loaded', function() {
foreach ( array ( 'blue', 'red', 'yellow' ) as $color )
add_post_meta( 561, 'color', $color, FALSE );
foreach ( array ( '14', '40', '104' ) as $age )
add_post_meta( 561, 'age', $age, FALSE );
});
The last parameter FALSE
tells WordPress not to make this meta key unique – to allow multiple values for one key.
The resulting structure in our postmeta
table will look like this:
Each row has a unique meta_id
, but each post_id
can have multiple meta_key
s, and each meta_key
can have multiple meta_value
s.
Now let’s fetch all custom values for post 561:
add_action( 'shutdown', function(){
$custom = get_post_custom( 561 );
print '<pre>' . esc_html( var_export( $custom, TRUE ) ) . '</pre>';
});
Result:
array (
'_edit_last' =>
array (
0 => '1',
),
'_edit_lock' =>
array (
0 => '1367617428:1',
),
'color' =>
array (
0 => 'blue',
1 => 'red',
2 => 'yellow',
),
'age' =>
array (
0 => '14',
1 => '40',
2 => '104',
),
)
_edit_last
and _edit_lock
are WordPress internals, we ignore that for the moment. Just note, we get these values an an array too, although there is just one value.
color
and age
are arrays like all post meta values.
$custom['color'][0]
is blue
.
Now we fetch just the color with get_post_meta()
:
add_action( 'shutdown', function(){
$color = get_post_meta( 561, 'color' );
print '<pre>' . esc_html( var_export( $color, TRUE ) ) . '</pre>';
});
Result:
array (
0 => 'blue',
1 => 'red',
2 => 'yellow',
)
We get just one piece of our meta values here. $color[0]
is still blue
. Behind the scenes, WordPress has already fetched all custom values, so a next hit for age
would be served from the cache.
In terms of performance get_post_custom()
and get_post_meta()
are equal.
Last attempt: Get the color with get_post_meta()
as a single value.
add_action( 'shutdown', function(){
$color = get_post_meta( 561, 'color', TRUE );
print '<pre>' . esc_html( var_export( $color, TRUE ) ) . '</pre>';
});
Result: blue
.
WordPress has done what you have done in your code: It has taken the array key 0
and returned the value as a string.
This is the most readable option, use it to write code that is easy to understand.