Codex tools: Log in
Contents |
This function returns the values of the custom fields with the specified key from the specified post. To return all of the custom fields, see get_post_custom(). See also update_post_meta(), delete_post_meta() and add_post_meta().
<?php $meta_values = get_post_meta($post_id, $key, $single); ?>
Please note that if your 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.
get_the_ID() while in The Loop to get the post's ID, or use your sub-loop's post object ID property (eg $my_post_object->ID). You may also use the global $post object's ID property (eg $post->ID), but this may not always be what you intend.
If there is nothing to return the function will return an empty array unless $single has been set to true, in which case an empty string is returned.
Get the meta for all keys:
<?php $meta = get_post_meta( get_the_ID() ); ?>
Get the meta for a single key:
<?php $key_1_values = get_post_meta(76, 'key_1'); ?>
<?php
$key_1_value = get_post_meta(get_the_ID(), 'key_1', true);
// check if the custom field has a value
if($key_1_value != '') {
echo $key_1_value;
}
?>
For a more detailed example, go to the post_meta Functions Examples page.
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".
<?php if ( get_post_meta(get_the_ID(), 'thumb', true) ) : ?>
<a href="<?php the_permalink() ?>" rel="bookmark">
<img class="thumb" src="<?php echo get_post_meta(get_the_ID(), 'thumb', true) ?>" alt="<?php the_title(); ?>" />
</a>
<?php endif; ?>
get_post_meta() is located in wp-includes/post.php
Custom Fields: the_meta(), get_post_meta(), add_post_meta(), update_post_meta(), delete_post_meta(), get_post_custom(), get_post_custom_values(), get_post_custom_keys() (See Also: post_meta Function Examples)