Using WordPress ‘get_post_meta_by_id()’ PHP function

The get_post_meta_by_id() WordPress PHP function retrieves post meta data by its meta ID.

Usage

To use the get_post_meta_by_id() function, pass the meta ID as an argument:

$meta_data = get_post_meta_by_id($mid);

Parameters

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

More information

See WordPress Developer Resources: get_post_meta_by_id

Examples

Retrieve post meta data by meta ID

This example retrieves post meta data by its meta ID and displays it.

$mid = 123; // Replace with your meta ID
$meta_data = get_post_meta_by_id($mid);
echo 'Meta Data: ' . $meta_data;

Check if post meta data exists

This example checks if post meta data exists for the given meta ID.

$mid = 456; // Replace with your meta ID
$meta_data = get_post_meta_by_id($mid);
if ($meta_data) {
    echo 'Meta Data exists';
} else {
    echo 'Meta Data not found';
}

Retrieve post meta data and post ID

This example retrieves both post meta data and its associated post ID by the meta ID.

$mid = 789; // Replace with your meta ID
$meta_data = get_post_meta_by_id($mid);
$post_id = $meta_data->post_id;
echo 'Post ID: ' . $post_id . ', Meta Data: ' . $meta_data->meta_value;

Display all post meta data for a specific post

This example retrieves all post meta data for a specific post and displays it.

$post_id = 1; // Replace with your post ID
$meta_data_array = get_post_meta($post_id);
foreach ($meta_data_array as $key => $value) {
    echo $key . ': ' . implode(', ', $value) . '<br>';
}

Update post meta data by meta ID

This example updates post meta data by its meta ID.

$mid = 101112; // Replace with your meta ID
$new_meta_value = 'Updated meta value'; // Replace with your new meta value
update_metadata_by_mid('post', $mid, $new_meta_value);