add_comment_meta()
云策文档标注
概述
add_comment_meta() 函数用于向评论添加元数据字段,是 WordPress 评论元数据管理的核心函数之一。它基于 add_metadata() 实现,支持多种数据类型存储,并具有历史遗留的转义要求。
关键要点
- 函数功能:向指定评论 ID 添加元数据键值对,可设置唯一性约束。
- 参数说明:$comment_id(评论 ID,必填)、$meta_key(元数据键名,必填)、$meta_value(元数据值,必填,支持数组、对象等序列化存储)、$unique(是否唯一,可选,默认 false)。
- 返回值:成功时返回元数据 ID,失败时返回 false。
- 历史注意事项:由于历史原因,输入时元键和元值需进行“转义”(斜杠转义)。
- 数据类型处理:数组和对象序列化存储,其他类型如布尔值、数字存储为字符串。
代码示例
// 添加评论元数据
$comment_id = 123;
$meta_key = 'user_rating';
$meta_value = 5;
add_comment_meta( $comment_id, $meta_key, $meta_value );注意事项
- 使用前需确保评论 ID 有效,避免无效操作。
- 注意元键的唯一性设置,防止重复添加相同键名。
- 存储非标量数据时,确保其可序列化。
原文内容
Adds meta data field to a comment.
Description
For historical reasons both the meta key and the meta value are expected to be “slashed” (slashes escaped) on input.
Parameters
$comment_idintrequired-
Comment 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_comment_meta( $comment_id, $meta_key, $meta_value, $unique = false ) {
return add_metadata( 'comment', $comment_id, $meta_key, $meta_value, $unique );
}
Changelog
| Version | Description |
|---|---|
| 2.9.0 | Introduced. |
Skip to note 3 content
Hitesh Patel
// Adding comment meta data
$comment_id = 123;
$meta_key = ‘user_rating’;
$meta_value = 5;
add_comment_meta( $comment_id, $meta_key, $meta_value );
$comment_id: The ID of the comment you want to attach the metadata to.
$meta_key: A unique key that identifies the type of metadata you are storing.
$meta_value: The value associated with the metadata. In this case, a numeric rating of 5.
This will add a custom field named user_rating with the value 5 to the comment with ID 123.
Skip to note 4 content
Codex
Basic Example
Add a custom posted value to every new comment