get_post_custom()
云策文档标注
概述
get_post_custom() 函数用于基于文章 ID 检索文章元字段,返回一个数组。它优先从缓存中获取数据,适合多次调用。
关键要点
- 函数基于 post ID 检索文章元字段,默认使用全局 $post 的 ID
- 返回值为数组,无效 post ID 返回 false,有效但不存在时返回空字符串
- 内部调用 get_post_meta(),并优化缓存以提高性能
- 相关函数包括 get_post_custom_keys() 和 get_post_custom_values()
代码示例
// 获取当前文章的所有自定义字段
$custom_fields = get_post_custom();
// 获取文章 ID 72 的特定自定义字段值
$custom_fields = get_post_custom(72);
if (isset($custom_fields['my_custom_field'])) {
foreach ($custom_fields['my_custom_field'] as $key => $value) {
echo $key . " => " . $value . "<br />";
}
}注意事项
- 函数返回多维数组,即使期望单值也需处理数组结构
- 存储为元值的数组会序列化,可能需要使用 maybe_unserialize 处理
原文内容
Retrieves post meta fields, based on post ID.
Description
The post meta fields are retrieved from the cache where possible, so the function is optimized to be called more than once.
Parameters
$post_idintoptional-
Post ID. Default is the ID of the global
$post.
Source
function get_post_custom( $post_id = 0 ) {
$post_id = absint( $post_id );
if ( ! $post_id ) {
$post_id = get_the_ID();
}
return get_post_meta( $post_id );
}
Changelog
| Version | Description |
|---|---|
| 1.2.0 | Introduced. |
Skip to note 2 content
Codex
Default Usage
Use the following example to set a variable ($custom_fields) as a multidimensional array containing all custom fields of the current post.
Retrieving data from the array
The following example will retrieve all custom field values with the key my_custom_field from post ID 72 (assuming there are three custom fields with this key, and the values are “dogs”, “47” and “This is another value”).
$value ) { echo $key . " => " . $value . "<br />"; } ?>0 => dogs
1 => 47
2 => This is another value
Note: not only does the function return a multi-dimensional array (ie: always be prepared to deal with an array of arrays, even if expecting array of single values), but it also returns serialized values of any arrays stored as meta values. If you expect that possibly an array may be stored as a metavalue, then be prepared to maybe_unserialize.