函数文档

register_term_meta()

💡 云策文档标注

概述

register_term_meta() 函数用于为分类法术语注册元数据键,允许开发者定义和管理术语的自定义字段。它基于 register_meta() 实现,支持跨所有现有分类法或指定分类法注册。

关键要点

  • 注册术语元数据键,参数包括 $taxonomy(分类法,空字符串表示所有分类法)、$meta_key(元键名)和 $args(参数数组)。
  • 返回布尔值,表示注册是否成功。
  • 内部调用 register_meta(),设置 object_subtype 为分类法。
  • 从 WordPress 4.9.8 版本引入。
  • 支持 REST API 集成,通过 show_in_rest 参数定义模式。

代码示例

register_term_meta( 'replica', 'nice_field', array(
    'type' => 'string',
    'description' => 'a nice description',
    'single' => true,
    'show_in_rest' => array(
        'schema' => array(
            'type' => 'string',
            'format' => 'url',
            'context' => array( 'view', 'edit' ),
            'readonly' => true,
       )
    ),
) );

注意事项

  • 虽然文档主要针对非标量值(数组和对象),但也可用于单值。
  • 在 WordPress 核心中,register_term_meta() 仅由 register_post_meta 和 register_term_meta 使用,其他核心功能未使用。
  • Jetpack 使用 register_post_meta() 和 register_meta() 处理 'post' 和 'user',但未使用 register_term_meta()。

📄 原文内容

Registers a meta key for terms.

Parameters

$taxonomystringrequired
Taxonomy to register a meta key for. Pass an empty string to register the meta key across all existing taxonomies.
$meta_keystringrequired
The meta key to register.
$argsarrayrequired
Data used to describe the meta key when registered. See register_meta() for a list of supported arguments.

Return

bool True if the meta key was successfully registered, false if not.

Source

function register_term_meta( $taxonomy, $meta_key, array $args ) {
	$args['object_subtype'] = $taxonomy;

	return register_meta( 'term', $meta_key, $args );
}

Changelog

Version Description
4.9.8 Introduced.

User Contributed Notes

  1. Skip to note 3 content

    Using this function with a specified schema makes its value available both in queries to get the value on the taxonomy and in the schema available through a request with OPTIONS method to the same endpoint.

    register_term_meta( 'replica', 'nice_field', array(
        'type' => 'string',
        'description' => 'a nice description',
        'single' => true,
        'show_in_rest' => array(
            'schema' => array(
                'type' => 'string',
                'format' => 'url',
                'context' => array( 'view', 'edit' ),
                'readonly' => true,
           )
        ),
    ) );

    Notes:
    – It is currently documented only for non scalar values (array and objects), but it’s valid using it for single values also.
    – It is available from version version 4.9.8