get_post_meta()

最后更新于:2021-11-26 22:33:34

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

Retrieves a post meta field for the given post ID.

参数

$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. This parameter has no effect if $key is not specified.

Default value: false

响应

(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.

源文件

文件: gc-includes/post.php

function get_post_meta( $post_id, $key = '', $single = false ) {
	return get_metadata( 'post', $post_id, $key, $single );
}
add_filter( 'get_post_metadata', 'add_dynamic_post_meta', 10, 4 );

/**
 * Add dynamically-generated "post meta" to `GC_Post` objects
 *
 * This makes it possible to access dynamic data related 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->_gc_page_template ?: 'not assigned' );
			break;
	}

	return $value;
}
/**
 Pass in function

	1: PostID                      =>     use get_the_ID();
	2: Meta Key Name               =>   'you can called anythings'
	3: Get The Post Meta Field     =>   get_post_meta();
	4: The Number Start Count      =>    add anyNumber ( 0,1,100,1000 or 2000 )
	5: Count +1
	6: Called Function in anypage  =>  <?php echo relationscode_save_post_views( ) ?>

 but you should remove (adjacent_posts_rel_link_gc_head)
**/

	function relationscode_post_views( ) {
       $postID = get_the_ID();
	   $metaKey = 'relationscode_post_views';
	   $views = get_post_meta( $postID, $metaKey, true );
	   $count_start_num = 0;
	
	   $count = ( empty( $views ) ? $count_start_num : $views );
       $count++;
    
       if(is_single()) {
    	  update_post_meta( $postID, $metaKey, $count );
    	  echo $count;
       } else {
    	   echo $views;
        
       }
	
   }
   remove_action( 'gc_head', 'adjacent_posts_rel_link_gc_head', 10, 0 );