函数文档

get_term_field()

💡 云策文档标注

概述

get_term_field() 函数用于获取经过 sanitize 处理的分类法术语字段值,确保数据安全。它简化了从术语对象中提取字段的流程,并依赖于 sanitize_term_field() 进行上下文相关的清理。

关键要点

  • 函数返回 sanitized 的术语字段值,如名称、描述等,基于指定上下文(如 'display'、'edit')。
  • 参数包括 $field(必需,字段名)、$term(必需,术语 ID 或 WP_Term 对象)、$taxonomy(可选,分类法名称)和 $context(可选,清理上下文,默认 'display')。
  • 返回值类型为 string、int、null 或 WP_Error,若 $term 无效或字段未设置则返回空字符串。
  • 内部调用 get_term() 获取术语对象,并使用 sanitize_term_field() 进行清理。
  • 相关函数包括 sanitize_term_field()、get_term() 和 is_wp_error(),用于数据获取和错误处理。

代码示例

function get_term_field( $field, $term, $taxonomy = '', $context = 'display' ) {
    $term = get_term( $term, $taxonomy );
    if ( is_wp_error( $term ) ) {
        return $term;
    }

    if ( ! is_object( $term ) ) {
        return '';
    }

    if ( ! isset( $term->$field ) ) {
        return '';
    }

    return sanitize_term_field( $field, $term->$field, $term->term_id, $term->taxonomy, $context );
}

注意事项

  • 从 WordPress 4.4.0 起,$taxonomy 参数变为可选,且 $term 可接受 WP_Term 对象,提高了灵活性。
  • 确保传递有效的 $field 名称,否则可能返回空字符串,影响数据展示。
  • 上下文参数 $context 影响清理方式,例如 'raw' 返回原始值,'display' 适合前端输出,需根据场景选择。

📄 原文内容

Gets sanitized term field.

Description

The function is for contextual reasons and for simplicity of usage.

See also

Parameters

$fieldstringrequired
Term field to fetch.
$termint|WP_Termrequired
Term ID or object.
$taxonomystringoptional
Taxonomy name. Default empty.
$contextstringoptional
How to sanitize term fields. Look at sanitize_term_field() for available options.
Default 'display'.

More Arguments from sanitize_term_field( … $context )

Context in which to sanitize the term field.
Accepts 'raw', 'edit', 'db', 'display', 'rss', 'attribute', or 'js'. Default 'display'.

Return

string|int|null|WP_Error Will return an empty string if $term is not an object or if $field is not set in $term.

Source

function get_term_field( $field, $term, $taxonomy = '', $context = 'display' ) {
	$term = get_term( $term, $taxonomy );
	if ( is_wp_error( $term ) ) {
		return $term;
	}

	if ( ! is_object( $term ) ) {
		return '';
	}

	if ( ! isset( $term->$field ) ) {
		return '';
	}

	return sanitize_term_field( $field, $term->$field, $term->term_id, $term->taxonomy, $context );
}

Changelog

Version Description
4.4.0 The $taxonomy parameter was made optional. $term can also now accept a WP_Term object.
2.3.0 Introduced.