Using WordPress ‘get_post_meta()’ PHP function

The get_post_meta() WordPress PHP function retrieves a post meta field for a given post ID.

Usage

get_post_meta($post_id, $key, $single);

Custom example:

// Get the 'author_name' post meta for post with ID 5
$author_name = get_post_meta(5, 'author_name', true);

Parameters

  • $post_id (int) – Required. The post ID.
  • $key (string) – Optional. The meta key to retrieve. By default, returns data for all keys. Default: ”.
  • $single (bool) – Optional. Whether to return a single value. This parameter has no effect if $key is not specified. Default: false.

More information

See WordPress Developer Resources: get_post_meta()

Examples

This code retrieves the ‘featured_image’ meta value for a post with ID 10.

$featured_image = get_post_meta(10, 'featured_image', true);

Retrieve all meta values for a post

This code retrieves all meta values for a post with ID 15.

$all_meta = get_post_meta(15);

Check if a post has a ‘price’ meta value

This code checks if a post with ID 20 has a ‘price’ meta value.

$has_price = get_post_meta(20, 'price', true);
if ($has_price) {
  echo 'This post has a price.';
}

Display a custom field ‘thumbnail_url’

This code displays the ‘thumbnail_url’ custom field of a post with ID 25.

$thumbnail_url = get_post_meta(25, 'thumbnail_url', true);
if ($thumbnail_url) {
  echo '<img src="' . esc_url($thumbnail_url) . '" alt="Thumbnail">';
}

Retrieve and display multiple values for ‘tags’ meta key

This code retrieves and displays multiple values for the ‘tags’ meta key of a post with ID 30.

$tags = get_post_meta(30, 'tags', false);
if (!empty($tags)) {
  foreach ($tags as $tag) {
    echo '<span class="tag">' . esc_html($tag) . '</span>';
  }
}