get_metadata()
云策文档标注
概述
get_metadata() 函数用于检索指定对象类型和 ID 的元数据字段值。它根据参数返回单个值或数组,并处理元数据不存在的情况。
关键要点
- 函数签名:get_metadata( $meta_type, $object_id, $meta_key = '', $single = false )
- 参数:$meta_type(必需,如 'post'、'user')、$object_id(必需)、$meta_key(可选,默认为空字符串)、$single(可选,默认为 false)
- 返回值:根据 $single 参数返回单个值或数组;无效输入返回 false;非序列化值以字符串形式返回(如 false 为 '',true 为 '1')
- 依赖函数:内部调用 get_metadata_raw() 和 get_metadata_default() 处理元数据检索和默认值
代码示例
// 示例:检索文章元数据数组
array (
'_pingme' => array (
0 => '1',
),
'_encloseme' => array (
0 => '1',
),
'custom key 1' => array (
0 => 'custom value 1',
1 => 'custom value 2',
),
'custom key 2' => array (
0 => 'custom value 3',
),
)注意事项
- 当元数据不存在且 $single 为 true 时返回空字符串,为 false 时返回空数组
- 无效 $object_id(非数字、零或负值)或未指定 $meta_type 时返回 false
- 相关函数包括 get_post_meta()、get_user_meta() 等特定对象类型的包装函数
原文内容
Retrieves the value of a metadata field for the specified object type and ID.
Description
If the meta field exists, a single value is returned if $single is true, or an array of values if it’s false.
If the meta field does not exist, the result depends on get_metadata_default() .
By default, an empty string is returned if $single is true, or an empty array if it’s false.
See also
Parameters
$meta_typestringrequired-
Type of object metadata is for. Accepts
'blog','post','comment','term','user', or any other object type with an associated meta table. $object_idintrequired-
ID of the object metadata is for.
$meta_keystringoptional-
Metadata key. If not specified, retrieve all metadata for the specified object. Default empty string.
$singlebooloptional-
If true, return only the first value of the specified
$meta_key.
This parameter has no effect if$meta_keyis not specified.Default:
false
Source
function get_metadata( $meta_type, $object_id, $meta_key = '', $single = false ) {
$value = get_metadata_raw( $meta_type, $object_id, $meta_key, $single );
if ( ! is_null( $value ) ) {
return $value;
}
return get_metadata_default( $meta_type, $object_id, $meta_key, $single );
}
Changelog
| Version | Description |
|---|---|
| 2.9.0 | Introduced. |
Skip to note 3 content
thenbrent
If the meta value does not exist and
true == $singlethe function will return an empty string (''). Iffalse == $singlean empty array is returned.If
! is_numeric( $user_id )or! absint( $user_id ), booleanfalseis returned.Skip to note 4 content
Sylvain Schellenberger
Example of returned array for post metadatas :
array ( '_pingme' => array ( 0 => '1', ), '_encloseme' => array ( 0 => '1', ), 'custom key 1' => array ( 0 => 'custom value 1', 1 => 'custom value 2', ), 'custom key 2' => array ( 0 => 'custom value 3', ), )