Retrieves a post meta field for the given post ID.
Parameters
$post_id
intrequired- Post ID.
$key
stringoptional- The meta key to retrieve. By default, returns data for all keys.
Default:
''
$single
booloptional- Whether to return a single value.
This parameter has no effect if$key
is not specified.
Default:
false
Return
mixed An array of values if$single
is false.The value of the meta field if
$single
is true.False for an invalid
$post_id
(non-numeric, zero, or negative value).An empty string if a valid but non-existing post ID is passed.
More Information
- 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.
Source
function get_post_meta( $post_id, $key = '', $single = false ) {
return get_metadata( 'post', $post_id, $key, $single );
}
Related
Uses | Description |
---|---|
get_metadata()wp-includes/meta.php | Retrieves the value of a metadata field for the specified object type and ID. |
Used by | Description |
---|---|
insert_hooked_blocks_into_rest_response()wp-includes/blocks.php | Hooks into the REST API response for the core/navigation block and adds the first and last inner blocks. |
update_ignored_hooked_blocks_postmeta()wp-includes/blocks.php | Updates the wp_postmeta with the list of ignored hooked blocks where the inner blocks are stored as post content. |
_wp_before_delete_font_face()wp-includes/fonts.php | Deletes associated font files when a font face is deleted. |
_block_bindings_post_meta_get_value()wp-includes/block-bindings/post-meta.php | Gets value for Post Meta source. |
_wp_preview_meta_filter()wp-includes/revision.php | Filters preview post meta retrieval to get values from the autosave. |
_wp_copy_post_meta()wp-includes/revision.php | Copy post meta for the given key from one post to another. |
wp_check_revisioned_meta_fields_have_changed()wp-includes/revision.php | Check whether revisioned post meta fields have changed. |
wp_autosave_post_revisioned_meta_fields()wp-admin/includes/post.php | Autosave the revisioned meta fields. |
update_menu_item_cache()wp-includes/nav-menu.php | Updates post and term caches for all linked objects for a list of menu items. |
_build_block_template_result_from_post()wp-includes/block-template-utils.php | Builds a unified template object based a post Object. |
get_media_states()wp-admin/includes/template.php | Retrieves an array of media states from an attachment. |
WP_REST_Attachments_Controller::edit_media_item()wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php | Applies edits to a media item and creates a new attachment record. |
get_post_states()wp-admin/includes/template.php | Retrieves an array of post states from a post. |
WP_User_Request::__construct()wp-includes/class-wp-user-request.php | Constructor. |
_wp_privacy_send_request_confirmation_notification()wp-includes/user.php | Notifies the site administrator via email when a request is confirmed. |
_wp_privacy_send_erasure_fulfillment_notification()wp-includes/user.php | Notifies the user when their erasure request is fulfilled. |
wp_check_for_changed_dates()wp-includes/post.php | Checks for changed dates for published post objects and save the old date. |
WP_Privacy_Policy_Content::get_suggested_policy_text()wp-admin/includes/class-wp-privacy-policy-content.php | Checks for updated, added or removed privacy policy information from plugins. |
WP_Privacy_Policy_Content::text_change_check()wp-admin/includes/class-wp-privacy-policy-content.php | Performs a quick check to determine whether any privacy info has changed. |
WP_Privacy_Policy_Content::_policy_page_updated()wp-admin/includes/class-wp-privacy-policy-content.php | Updates the cached policy info when the policy page is updated. |
wp_privacy_process_personal_data_export_page()wp-admin/includes/privacy-tools.php | Intercept personal data exporter page Ajax responses in order to assemble the personal data export file. |
wp_privacy_generate_personal_data_export_file()wp-admin/includes/privacy-tools.php | Generate the personal data export file. |
wp_privacy_send_personal_data_export_email()wp-admin/includes/privacy-tools.php | Send an email to the user with a link to the personal data export file |
WP_Customize_Manager::set_changeset_lock()wp-includes/class-wp-customize-manager.php | Marks the changeset post as being currently edited by the current user. |
WP_Customize_Manager::refresh_changeset_lock()wp-includes/class-wp-customize-manager.php | Refreshes changeset lock with the current time if current user edited the changeset before. |
WP_Customize_Manager::import_theme_starter_content()wp-includes/class-wp-customize-manager.php | Imports theme starter content into the customized state. |
WP_REST_Attachments_Controller::prepare_item_for_response()wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php | Prepares a single attachment output for response. |
WP_Customize_Nav_Menus::save_nav_menus_created_posts()wp-includes/class-wp-customize-nav-menus.php | Publishes the auto-draft posts that were created for nav menu items. |
get_custom_logo()wp-includes/general-template.php | Returns a custom logo, linked to home unless the theme supports removing the link on the home page. |
get_header_image_tag()wp-includes/theme.php | Creates image tag markup for a custom header image. |
wp_ajax_crop_image()wp-admin/includes/ajax-actions.php | Handles cropping an image via AJAX. |
wp_restore_image()wp-admin/includes/image-edit.php | Restores the metadata for a given attachment. |
wp_save_image()wp-admin/includes/image-edit.php | Saves image to post, along with enqueued changes in |
wp_image_editor()wp-admin/includes/image-edit.php | Loads the WP image-editing interface. |
edit_form_image_editor()wp-admin/includes/media.php | Displays the image and editor in the post editor |
get_attachment_fields_to_edit()wp-admin/includes/media.php | Retrieves the attachment fields to edit form fields. |
media_upload_form_handler()wp-admin/includes/media.php | Handles form submissions for the legacy media uploader. |
wp_check_post_lock()wp-admin/includes/post.php | Determines whether the post is currently being edited by another user. |
edit_post()wp-admin/includes/post.php | Updates an existing post with values provided in |
wp_ajax_wp_fullscreen_save_post()wp-admin/includes/ajax-actions.php | Handles saving posts from the fullscreen editor via AJAX. |
wp_ajax_save_attachment()wp-admin/includes/ajax-actions.php | Handles updating attachment attributes via AJAX. |
post_thumbnail_meta_box()wp-admin/includes/meta-boxes.php | Displays post thumbnail meta box. |
post_submit_meta_box()wp-admin/includes/meta-boxes.php | Displays post submit form fields. |
Custom_Image_Header::get_uploaded_header_images()wp-admin/includes/class-custom-image-header.php | Gets the previously uploaded header images. |
map_meta_cap()wp-includes/capabilities.php | Maps a capability to the primitive capabilities required of the given user to satisfy the capability being checked. |
get_uploaded_header_images()wp-includes/theme.php | Gets the header images uploaded for the active theme. |
WP_Embed::shortcode()wp-includes/class-wp-embed.php | The do_shortcode() callback function. |
get_post_thumbnail_id()wp-includes/post-thumbnail-template.php | Retrieves the post thumbnail ID. |
_wp_menu_item_classes_by_context()wp-includes/nav-menu-template.php | Adds the class property classes for the current context, if applicable. |
get_page_template_slug()wp-includes/post-template.php | Gets the specific template filename for a given post. |
WP_Post::__get()wp-includes/class-wp-post.php | Getter. |
wp_check_for_changed_slugs()wp-includes/post.php | Checks for changed slugs for published post objects and save the old slug. |
wp_delete_attachment()wp-includes/post.php | Trashes or deletes an attachment. |
wp_get_attachment_metadata()wp-includes/post.php | Retrieves attachment metadata for attachment ID. |
wp_get_attachment_url()wp-includes/post.php | Retrieves the URL for an attachment. |
wp_untrash_post_comments()wp-includes/post.php | Restores comments for a post from the Trash. |
wp_insert_post()wp-includes/post.php | Inserts or update a post. |
wp_untrash_post()wp-includes/post.php | Restores a post from the Trash. |
get_post_custom()wp-includes/post.php | Retrieves post meta fields, based on post ID. |
get_post_status()wp-includes/post.php | Retrieves the post status based on the post ID. |
get_attached_file()wp-includes/post.php | Retrieves attached file path based on attachment ID. |
get_the_modified_author()wp-includes/author-template.php | Retrieves the author who last edited the current post. |
wp_setup_nav_menu_item()wp-includes/nav-menu.php | Decorates a menu item object with the shared navigation menu item properties. |
wp_get_associated_nav_menu_items()wp-includes/nav-menu.php | Returns the menu items associated with a particular object. |
wp_update_nav_menu_item()wp-includes/nav-menu.php | Saves the properties of a menu item or create a new one. |
wp_xmlrpc_server::add_enclosure_if_new()wp-includes/class-wp-xmlrpc-server.php | Adds an enclosure to a post if it’s new. |
wp_xmlrpc_server::_prepare_post()wp-includes/class-wp-xmlrpc-server.php | Prepares post data for return in an XML-RPC object. |
wp_xmlrpc_server::_prepare_media_item()wp-includes/class-wp-xmlrpc-server.php | Prepares media item data for return in an XML-RPC object. |
Changelog
Version | Description |
---|---|
1.5.0 | Introduced. |
Return values when no meta field is found
If a meta field with the given $key isn’t found for the given $post_id, the return value varies:
If $single is true, an empty string is returned.
If $single is false, an empty array is returned.
Since both evaluate as false, you can use get_post_meta directly in conditionals, like this:
What if I want to store an empty string?
If for some reason your with to store an empty string or array into your meta field, get_post_meta will not be reliable when checking if the given meta field exists.
In this case, you can use get_post_custom_keys to do so:
The best thing about this function is that you no longer need to use it :)
Since r21559 (v3.5), you can just call
$post->foo
to fetch the equivalent ofget_post_meta( $post->ID, 'foo', true )
.You can even extend that to introduce dynamically-generated fields, so you can call
echo esc_html( $post->bar )
instead of$bar = some_custom_logic( get_post_meta( $post->ID, 'bar', true ) ); echo esc_html( $bar )
.This makes code a lot cleaner and more readable.
$post->bar
will only return the first value.get_post_meta( get_the_ID(), 'bar')
will return all the values for the key “bar”. Multiple values can be added to a key using theadd_post_meta
function. Values can be removed withdelete_post_meta
.Show the first value of the specified key inside a loop
Default Usage
Get the meta for all keys for the current post:
Get all meta for a single key for the current post:
Get the first value of a meta key for the current post:
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”.
When you don’t specify a $key (”) and set $single to true in get_post_meta, it will return all keys still with an array of values.
If you want to hide postmeta keys from the customfields prefix the key name with an underscore.
When we calling for all post meta, it will returned array value:
sample output:
We can make it into string, array_column will resulting default array value into string, for sure we need array combine to re-form array key:
now output will be like here:
Display single meta value using meta key
Post meta keys are case-sensitive
If the value of the
$key
parameter is falsyget_post_meta
will return the entire post meta array, even if$single
is set totrue
. for example:Function The Retrieve a Number views in post
Note that to add or set post meta values you can use the function
add_post_meta
:Here’s a pitfall to steer clear of…
register_post_meta() allows you to define a default value for a meta field. If the default value evaluates to true, you’ll be scratching your head why get_post_meta() returns true when you haven’t yet set a value, or just used delete_post_meta() .
Obviously get_post_meta() will return the default value defined in register_post_meta() .
False if post ID isn’t absint or is 0
Passing
$post_id == 0
(or anything not a absint) will return false no matter$single
.