Using WordPress ‘has_meta()’ PHP function

The has_meta() WordPress PHP function returns the meta data for a given post ID.

Usage

To use the has_meta() function, simply provide the post ID as an argument:

$post_meta = has_meta($post_id);

Parameters

  • $post_id (int) – Required. The ID of the post for which you want to retrieve the meta data.

More information

See WordPress Developer Resources: has_meta()

Examples

Get post meta data

In this example, we will get the meta data for a post with an ID of 42.

$post_id = 42;
$post_meta = has_meta($post_id);

Display meta data

Retrieve the meta data for a post and display it.

$post_id = 123;
$post_meta = has_meta($post_id);

if ($post_meta) {
    foreach ($post_meta as $meta) {
        echo 'Meta key: ' . $meta['meta_key'] . ', Meta value: ' . $meta['meta_value'] . '<br>';
    }
}

Check if a specific meta key exists

Check if a post has a specific meta key.

$post_id = 456;
$specific_meta_key = 'my_custom_key';
$post_meta = has_meta($post_id);

if ($post_meta) {
    $found = false;
    foreach ($post_meta as $meta) {
        if ($meta['meta_key'] == $specific_meta_key) {
            $found = true;
            break;
        }
    }
    if ($found) {
        echo 'Meta key found!';
    } else {
        echo 'Meta key not found.';
    }
}

Count the number of meta data entries

Count the number of meta data entries for a post.

$post_id = 789;
$post_meta = has_meta($post_id);

if ($post_meta) {
    $meta_count = count($post_meta);
    echo 'Number of meta data entries: ' . $meta_count;
}

Remove a specific meta key

Remove a specific meta key from a post.

$post_id = 101112;
$specific_meta_key = 'my_custom_key_to_remove';
$post_meta = has_meta($post_id);

if ($post_meta) {
    foreach ($post_meta as $meta) {
        if ($meta['meta_key'] == $specific_meta_key) {
            delete_post_meta($post_id, $specific_meta_key);
            echo 'Meta key removed!';
            break;
        }
    }
}