get_post_meta ( int $post_id, string $key = '', bool $single = false )

Retrieve post meta field for a post.

Return: (mixed) Will be an array if $single is false. Will be value of meta data field if $single is true.

Source file: wp-includes/post.php

View source


Parameters

$post_id

(int) (Required) Post ID.

$key

(string) (Optional) The meta key to retrieve. By default, returns data for all keys.

Default value: ''

$single

(bool) (Optional) Whether to return a single value.

Default value: false


Explanation

  • Please note that if a db collation is case insensitive (has with suffix _ci) then update_post_meta and delete_post_meta and get_posts() will update/delete/query the meta records with keys that are upper or lower case. However get_post_meta will apparently be case sensitive due to WordPress caching. See https://core.trac.wordpress.org/ticket/18210 for more info. Be careful not to mix upper and lowercase.
  • Uses: get_metadata() to retrieve the metadata.

Used by


Source

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


Changelog


User Contributed Notes

  1. Default Usage
    Get the meta for all keys for the current post:

    <?php $meta = get_post_meta( get_the_ID() ); ?>
    

    Get all meta for a single key for the current post:

    <?php $key_1_values = get_post_meta( get_the_ID(), 'key_1' ); ?>
    

    Get the first value of a meta key for the current post:

    <?php $key_1_value = get_post_meta( get_the_ID(), 'key_1', true ); ?>
    
  2. Show the first value of the specified key inside a loop

    $key_1_value = get_post_meta( get_the_ID(), 'key_1', true );
    // Check if the custom field has a value.
    if ( ! empty( $key_1_value ) ) {
    	echo $key_1_value;
    }
    
  3. Retrieve a Custom Field Thumbnail Url
    While you are in the WordPress Loop, you can use this code to retrieve a custom field. In this example, the thumbnail image url is in a custom field named “thumb”.

    <?php if ( get_post_meta( get_the_ID(), 'thumb', true ) ) : ?>
    	<a href="<?php the_permalink() ?>" rel="bookmark">
    		<img class="thumb" src="<?php echo esc_url( get_post_meta( get_the_ID(), 'thumb', true ) ); ?>" alt="<?php the_title_attribute(); ?>" />
    	</a>
    <?php endif; ?>
    

You must log in before being able to contribute a note.