post: Checking for meta data in WordPress


Checking for meta data in WordPress

Working With WordPress



Post-Meta Taxonomy Meta WordPress

Meta data is key:value paired data associated with posts, taxonomies and users in WordPress. Post meta data is stored in the wp_post_meta table, taxonomy term meta data in the wp_term_meta table and user meta data in the wp_user_meta data table.

Post Meta Retrieval

One common question is how to check that post meta data exists. Here are the 3 most commonly used methods:

1. get_post_meta

$key_value = get_post_meta( get_the_ID(), 'key', true );
// Check if the custom field has a value.
if ( ! empty( $key_1_value ) ) {
    echo $key_1_value;

It is a wrapper of the get_metadata function:

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

If the last argument is true a single value is retrieved, otherwise an array is returned. If no meta data is stored then an empty string or array is returned. It’s functional in most instances, but doesn’t tell whether the actual post meta key:value is set.

2. get_post_custom

$meta_data = get_post_custom(get_the_ID());
if ( array_key_exists('key', $meta_data) ) { 
  if ( is_array( $meta_data['key'] ) ) { 
    print_r( $meta_data['key'], true ) 
  } else { 
    echo $meta_data['key']; 

The function retrieves all post_meta key:value pairs for the post ID. Depending on the range of data stored this may be a significant set of values.

3. Metadata_exists

This is the least well known method but the most useful result.

$has_meta = metadata_exists( 'post', get_the_ID(), 'key' );
if ( $has_meta ) {
$key_value = get_post_meta( get_the_ID(), 'key', true );
echo $key_value;

Which one to use? Depends on the circumstance. For displaying data to screen, where if you’re not bothered about the state of the value then the first method. If you’re processing data for storage, e.g. within a plugin, then I would use method 3. It is the one I use for setting / testing data in my custom post type / taxonomy plugin.

comments powered by Disqus