add_term_meta()
云策文档标注
概述
add_term_meta() 函数用于向 WordPress 分类法术语添加元数据,是处理术语自定义字段的核心函数。它基于 add_metadata() 实现,但包含对共享术语的特殊处理。
关键要点
- 函数用于向指定术语 ID 添加元数据键值对,支持唯一性检查。
- 参数包括 term_id(整数,必需)、meta_key(字符串,必需)、meta_value(混合类型,必需,非标量需可序列化)和 unique(布尔值,可选,默认 false)。
- 返回值:成功时返回元数据 ID,失败时返回 false,当 term_id 在分类法间不明确时返回 WP_Error。
- 历史原因要求输入时元键和元值需进行“斜杠转义”。
- 元值存储规则:数组和对象序列化存储,false 存储为空字符串,true 存储为 '1',数字存储为字符串。
- 内部使用 wp_term_is_shared() 检查共享术语,避免向共享术语添加元数据。
代码示例
add_term_meta( 12, "my_term_key", 'new_term' );注意事项
向共享术语添加元数据会返回 WP_Error,错误消息为“Term meta cannot be added to terms that are shared between taxonomies.”。函数自 WordPress 4.4.0 版本引入。
原文内容
Adds metadata to a term.
Description
For historical reasons both the meta key and the meta value are expected to be “slashed” (slashes escaped) on input.
Parameters
$term_idintrequired-
Term 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_term_meta( $term_id, $meta_key, $meta_value, $unique = false ) {
if ( wp_term_is_shared( $term_id ) ) {
return new WP_Error( 'ambiguous_term_id', __( 'Term meta cannot be added to terms that are shared between taxonomies.' ), $term_id );
}
return add_metadata( 'term', $term_id, $meta_key, $meta_value, $unique );
}
Changelog
| Version | Description |
|---|---|
| 4.4.0 | Introduced. |
Skip to note 2 content
Abiral Neupane
Usage
Example
Adds a new custom field with a key name ‘my_term_key’ and value as ‘new_term’
add_term_meta( 12, "my_term_key" , 'new_term' );