Using WordPress ‘metadata_exists()’ PHP function

The metadata_exists() WordPress PHP function checks if a meta field with the given key exists for the specified object ID.

Usage

To use the function, provide the type of object metadata is for, the object ID, and the metadata key.

metadata_exists( $meta_type, $object_id, $meta_key );

Parameters

  • $meta_type (string) – Required. Type of object metadata is for. Accepts ‘post’, ‘comment’, ‘term’, ‘user’, or any other object type with an associated meta table.
  • $object_id (int) – Required. ID of the object metadata is for.
  • $meta_key (string) – Required. Metadata key.

More information

See WordPress Developer Resources: metadata_exists

Examples

Check if term metadata exists and retrieve it

if (metadata_exists('term', $term_id, '_meta_key')) {
    $meta_value = get_term_meta($term_id, '_meta_key', true);
}

Check if post metadata exists and retrieve it

if (metadata_exists('post', $post_id, '_meta_key')) {
    $meta_value = get_post_meta($post_id, '_meta_key', true);
}

Check if user metadata exists and retrieve it

if (metadata_exists('user', $user_id, '_meta_key')) {
    $meta_value = get_user_meta($user_id, '_meta_key', true);
}

Check if comment metadata exists and retrieve it

if (metadata_exists('comment', $comment_id, '_meta_key')) {
    $meta_value = get_comment_meta($comment_id, '_meta_key', true);
}

Check if custom object type metadata exists and retrieve it

if (metadata_exists('custom_object', $custom_object_id, '_meta_key')) {
    $meta_value = get_metadata('custom_object', $custom_object_id, '_meta_key', true);
}