板邓:WordPress页面或文章自定义字段函数

get_post_meta()函数意义详解

This function returns the values of the custom fields with the specified key from the specified post.

中文的大概意思是,该函数用于取出用户设置的自定义字段。
像许多以get开头的诸如:get_post_class、get_posts一样,只是将结果返回,而不直接显示与页面,在使用的时候要留意下。

用法

<?php $meta_values = get_post_meta($post_id, $key, $single); ?>

参数解释


$post_id
文章的ID(如果在循环中,你可以用 get_the_ID()来设置),
$key自定义字段的名称(键值),
$single是否以字符串形式返回,false会返回数组形式。

实例

以下代码可用于index.php进行测试

 if (have_posts()) ://如果有文章
 while (have_posts()) : the_post(); //开启主循环
   $xzmeta  = get_post_meta(get_the_ID(),'xzmeta',true);
 endwhile; 
 endif;
  • 如果没有设置”xzmeta”这个自定义字段的话,$xzmeta 会是false
  • 如果有设置,则返回设置的值。
  • 如果第三个参数设置为false,则返回数组,且相同键值的自定义字段的值会按照添加顺序组合成一个序列数组。
  • 如果只设置$postid参数,那将返回所有的自定义字段值。用法类似于使用get_post_custom()函数

函数声明

/**
 * Retrieve post meta field for a post.
 *
 * @since 1.5.0
 * @uses $wpdb
 * @link http://codex.wordpress.org/Function_Reference/get_post_meta
 *
 * @param int $post_id Post ID.
 * @param string $key Optional. The meta key to retrieve. By default, returns data for all keys.
 * @param bool $single Whether to return a single value.
 * @return mixed Will be an array if $single is false. Will be value of meta data field if $single
 *  is true.
 */
function get_post_meta($post_id, $key = '', $single = false) {
	return get_metadata('post', $post_id, $key, $single);
}

总结

后面有可能会讲一下三个配套使用的函数,虽然这三个函数用处不会很多。

  1. add_post_meta(),
  2. update_post_meta(),
  3. delete_post_meta(),

还有自定义字段的扩展用法相关的函数。

  1. get_post_custom(),
  2. get_post_custom_values(),
  3. get_post_custom_keys()。
posted @ 2017-11-17 11:52  贵隆  阅读(232)  评论(0编辑  收藏  举报