函数文档

update_term_meta()

💡 云策文档标注

概述

update_term_meta() 函数用于更新分类法术语的元数据,支持通过 $prev_value 参数区分相同键和术语 ID 的元字段,并在元字段不存在时自动添加。由于历史原因,输入时元键和元值需要转义斜杠。

关键要点

  • 函数更新指定术语 ID 的元数据,若元键不存在则添加新元字段。
  • 参数 $prev_value 可选,用于仅更新具有特定值的现有元数据条目,否则更新所有条目。
  • 返回类型多样:元 ID(如果键不存在)、true(成功更新)、false(失败或值未变)或 WP_Error(当术语 ID 在分类法间不明确时)。
  • 内部调用 update_metadata(),并检查术语是否在多个分类法间共享以避免歧义。

代码示例

$term_id = 23;

update_term_meta( $term_id, 'meta_key', 'Hello world!' );

注意事项

  • 输入时元键和元值需转义斜杠("slashed"),这是历史遗留要求。
  • 非标量元值必须可序列化。
  • 如果术语 ID 在多个分类法间共享,函数返回 WP_Error 以避免数据混淆。

📄 原文内容

Updates term metadata.

Description

Use the $prev_value parameter to differentiate between meta fields with the same key and term ID.

If the meta field for the term does not exist, it will be added.

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 key.
$meta_valuemixedrequired
Metadata value. Must be serializable if non-scalar.
$prev_valuemixedoptional
Previous value to check before updating.
If specified, only update existing metadata entries with this value. Otherwise, update all entries. Default empty.

Return

int|bool|WP_Error Meta ID if the key didn’t exist. true on successful update, false on failure or if the value passed to the function is the same as the one that is already in the database.
WP_Error when term_id is ambiguous between taxonomies.

Source

function update_term_meta( $term_id, $meta_key, $meta_value, $prev_value = '' ) {
	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 update_metadata( 'term', $term_id, $meta_key, $meta_value, $prev_value );
}

Changelog

Version Description
4.4.0 Introduced.

User Contributed Notes