返回介绍

get_post_meta()

发布于 2017-09-10 23:54:01 字数 13053 浏览 1086 评论 0 收藏 0

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

Retrieve post meta field for a post.


description


参数

$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


返回值

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


源代码

File: wp-includes/post.php

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

更新日志

Versiondescription
1.5.0Introduced.

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.

相关函数

Uses

  • wp-includes/meta.php: get_metadata()

Used By

  • wp-includes/class-wp-customize-manager.php: WP_Customize_Manager::import_theme_starter_content()
  • wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php: WP_REST_Attachments_Controller::prepare_item_for_response()
  • wp-includes/class-wp-customize-nav-menus.php: WP_Customize_Nav_Menus::save_nav_menus_created_posts()
  • wp-includes/general-template.php: get_custom_logo()
  • wp-includes/theme.php: get_header_image_tag()
  • wp-admin/includes/ajax-actions.php: wp_ajax_crop_image()
  • wp-admin/includes/image-edit.php: wp_restore_image()
  • wp-admin/includes/image-edit.php: wp_save_image()
  • wp-admin/includes/image-edit.php: wp_image_editor()
  • wp-admin/includes/template.php: _media_states()
  • wp-admin/includes/media.php: edit_form_image_editor()
  • wp-admin/includes/media.php: get_attachment_fields_to_edit()
  • wp-admin/includes/media.php: media_upload_form_handler()
  • wp-admin/includes/post.php: wp_check_post_lock()
  • wp-admin/includes/post.php: edit_post()
  • wp-admin/includes/ajax-actions.php: wp_ajax_wp_fullscreen_save_post()
  • wp-admin/includes/ajax-actions.php: wp_ajax_save_attachment()
  • wp-admin/includes/meta-boxes.php: post_thumbnail_meta_box()
  • wp-admin/custom-header.php: Custom_Image_Header::get_uploaded_header_images()
  • wp-includes/capabilities.php: map_meta_cap()
  • wp-includes/theme.php: get_uploaded_header_images()
  • wp-includes/class-wp-embed.php: WP_Embed::shortcode()
  • wp-includes/post-thumbnail-template.php: get_post_thumbnail_id()
  • wp-includes/nav-menu-template.php: _wp_menu_item_classes_by_context()
  • wp-includes/post-template.php: get_page_template_slug()
  • wp-includes/media.php: wp_maybe_generate_attachment_metadata()
  • wp-includes/media.php: wp_prepare_attachment_for_js()
  • wp-includes/media.php: wp_enqueue_media()
  • wp-includes/media.php: wp_get_attachment_image()
  • wp-includes/class-wp-post.php: WP_Post::__get()
  • wp-includes/post.php: wp_check_for_changed_slugs()
  • wp-includes/post.php: wp_delete_attachment()
  • wp-includes/post.php: wp_get_attachment_metadata()
  • wp-includes/post.php: wp_get_attachment_url()
  • wp-includes/post.php: wp_untrash_post_comments()
  • wp-includes/post.php: wp_insert_post()
  • wp-includes/post.php: wp_untrash_post()
  • wp-includes/post.php: get_post_custom()
  • wp-includes/post.php: get_post_status()
  • wp-includes/post.php: get_attached_file()
  • wp-includes/author-template.php: get_the_modified_author()
  • wp-includes/nav-menu.php: wp_setup_nav_menu_item()
  • wp-includes/nav-menu.php: wp_get_associated_nav_menu_items()
  • wp-includes/nav-menu.php: wp_update_nav_menu_item()
  • wp-includes/nav-menu.php: wp_get_nav_menu_items()
  • wp-includes/class-wp-xmlrpc-server.php: wp_xmlrpc_server::add_enclosure_if_new()
  • wp-includes/class-wp-xmlrpc-server.php: wp_xmlrpc_server::_prepare_post()
  • Show 42 more used by Hide more used by

User Contributed Notes

  1. Skip to note content You must log in to vote on the helpfulness of this noteVote results for this note: 16You must log in to vote on the helpfulness of this note Contributed by memuller

    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:

    
    if( ! get_post_meta( '1', 'non-existing_meta', true ) ) {}
    if( ! get_post_meta( '1', 'non-existing_meta', false ) ) {}
    // both ifs will get run if no meta field is found; since
    // array() == false and '' == false
    

    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:

    
    if( ! in_array( 'given_key', get_post_custom_keys( '1' ) ) ) {} 
    // this correctly checks for the existence of the given key, 
    // even if it's empty or has a value that evaluates as false. 
    
  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;
    }
    

    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 ); ?>
    

    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; ?>
    

    If you want to hide postmeta keys from the customfields prefix the key name with an underscore.

    Post meta keys are case-sensitive

    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 of get_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.

    
    add_filter( 'get_post_metadata', 'add_dynamic_post_meta', 10, 4 );
    
    /**
     * Add dynamically-generated "post meta" to `\WP_Post` objects
     *
     * This makes it possible to access dynamic data 相关函数 to a post object by simply referencing `$post->foo`.
     * That keeps the calling code much cleaner than if it were to have to do something like
     * `$foo = some_custom_logic( get_post_meta( $post->ID, 'bar', true ) ); echo esc_html( $foo )`.
     *
     * @param mixed  $value
     * @param int    $post_id
     * @param string $meta_key
     * @param int    $single   @todo handle the case where this is false
     *
     * @return mixed
     *      `null` to instruct `get_metadata()` to pull the value from the database
     *      Any non-null value will be returned as if it were pulled from the database
     */
    function add_dynamic_post_meta( $value, $post_id, $meta_key, $single ) {
    	$post = get_post( $post_id );
    
    	if ( 'page' != $post->post_type ) {
    		return $value;
    	}
    
    	switch ( $meta_key ) {
    		case 'verbose_page_template':
    			$value = "The page template is " . ( $post->_wp_page_template ?: 'not assigned' );
    			break;
    	}
    
    	return $value;
    }
    

    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.

    
    $meta = get_post_meta(get_the_ID(), '', true);
    print_r($meta);
    //Array ( [key_1] => Array ( [0] => value_1 ), [key_2] => Array ( [0] => value_2 ) )
    

    Display single meta value using meta key

    
    <?php 
    $meta_print_value=get_post_meta(get_the_ID(),'conference_speaker_business',true);
    echo($meta_print_value);
    ?>
    

    If the value of the $key parameter is falsy get_post_meta will return the entire post meta array, even if $single is set to true. for example:

    get_post_meta( $post_id, FALSE, TRUE); //Returns all the post meta fields as an array.
    get_post_meta( $post_id, '0', TRUE); //Will also return all the post meta fields as an array. 

    When I had tons of meta keys to work with to display some custom content for custom post types, instead of making several dozen calls to the get_post_meta function to grab the keys I wanted, I wrote this function instead. Basically it gets all of the meta keys and filters out all of the arrays with single values while maintaining any arrays that actually do have multiple values and returns an associative array of the results. If you have lots of single values to get, it saves you from having to iterate over every result to get your $k=>$v pairs so you can just access them by $mk[‘my_custom_meta_key’].
    function array_push_assoc($array, $key, $value){
    $array[$key] = $value;
    return $array;
    }

    function filter_gpm($array){
    $mk = array();
    foreach($array as $k => $v){
    if(is_array($v) && count($v) == 1){
    $mk = array_push_assoc($mk, $k, $v[0]);
    } else {
    $mk = array_push_assoc($mk, $k, $v);
    }
    }
    return $mk;
    }
    Call it like so
    $mk = filter_gpm( get_post_meta( get_the_ID() ) );

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文