add_user_meta()
云策文档标注
概述
add_user_meta() 函数用于向用户添加元数据,是 WordPress 用户元数据管理的基础函数。它基于 add_metadata() 实现,支持多种数据类型存储,并具有唯一性控制选项。
关键要点
- 函数功能:向指定用户 ID 添加元数据键值对。
- 参数说明:$user_id(用户 ID,整数,必需)、$meta_key(元数据键名,字符串,必需)、$meta_value(元数据值,混合类型,必需)、$unique(是否唯一,布尔值,可选,默认 false)。
- 数据类型处理:数组和对象以序列化形式存储,其他类型(如布尔值、数字)转换为字符串存储。
- 返回值:成功时返回元数据 ID(整数),失败时返回 false。
- 历史兼容性:输入时元数据键和值需进行“斜杠转义”(slashed)。
代码示例
function add_user_meta( $user_id, $meta_key, $meta_value, $unique = false ) {
return add_metadata( 'user', $user_id, $meta_key, $meta_value, $unique );
}
原文内容
Adds meta data to a user.
Description
For historical reasons both the meta key and the meta value are expected to be “slashed” (slashes escaped) on input.
Parameters
$user_idintrequired-
User ID.
$meta_keystringrequired-
Metadata name.
$meta_valuemixedrequired-
Metadata value. Arrays and objects are stored as serialized data and will be returned as the same type when retrieved. Other data types will be stored as strings in the database:
- false is stored and retrieved as an empty string (
'') - true is stored and retrieved as
'1' - numbers (both integer and float) are stored and retrieved as strings Must be serializable if non-scalar.
- false is stored and retrieved as an empty string (
$uniquebooloptional-
Whether the same key should not be added.
Default:
false
Source
function add_user_meta( $user_id, $meta_key, $meta_value, $unique = false ) {
return add_metadata( 'user', $user_id, $meta_key, $meta_value, $unique );
}
Changelog
| Version | Description |
|---|---|
| 3.0.0 | Introduced. |
Skip to note 2 content
Codex
Examples