函数文档

sanitize_term()

💡 云策文档标注

概述

sanitize_term() 函数用于清理所有 term 字段,基于 sanitize_term_field() 实现,支持数组或对象形式的 term 输入,并返回清理后的 term。

关键要点

  • 函数 sanitize_term() 清理 term 的所有字段,包括 term_id、name、description、slug、count、parent、term_group、term_taxonomy_id 和 object_id。
  • 参数 $term 可以是数组或对象,$taxonomy 为必需参数指定分类法名称,$context 可选,默认为 'display',用于指定清理上下文。
  • 函数内部通过循环遍历字段,调用 sanitize_term_field() 进行清理,并设置 filter 属性为 $context。

代码示例

function sanitize_term( $term, $taxonomy, $context = 'display' ) {
	$fields = array( 'term_id', 'name', 'description', 'slug', 'count', 'parent', 'term_group', 'term_taxonomy_id', 'object_id' );

	$do_object = is_object( $term );

	$term_id = $do_object ? $term->term_id : ( isset( $term['term_id'] ) ? $term['term_id'] : 0 );

	foreach ( (array) $fields as $field ) {
		if ( $do_object ) {
			if ( isset( $term->$field ) ) {
				$term->$field = sanitize_term_field( $field, $term->$field, $term_id, $taxonomy, $context );
			}
		} else {
			if ( isset( $term[ $field ] ) ) {
				$term[ $field ] = sanitize_term_field( $field, $term[ $field ], $term_id, $taxonomy, $context );
			}
		}
	}

	if ( $do_object ) {
		$term->filter = $context;
	} else {
		$term['filter'] = $context;
	}

	return $term;
}

📄 原文内容

Sanitizes all term fields.

Description

Relies on sanitize_term_field() to sanitize the term. The difference is that this function will sanitize all fields. The context is based on sanitize_term_field() .

The $term is expected to be either an array or an object.

Parameters

$termarray|objectrequired
The term to check.
$taxonomystringrequired
The taxonomy name to use.
$contextstringoptional
Context in which to sanitize the term.
Accepts 'raw', 'edit', 'db', 'display', 'rss', 'attribute', or 'js'. Default 'display'.

Return

array|object Term with all fields sanitized.

Source

function sanitize_term( $term, $taxonomy, $context = 'display' ) {
	$fields = array( 'term_id', 'name', 'description', 'slug', 'count', 'parent', 'term_group', 'term_taxonomy_id', 'object_id' );

	$do_object = is_object( $term );

	$term_id = $do_object ? $term->term_id : ( isset( $term['term_id'] ) ? $term['term_id'] : 0 );

	foreach ( (array) $fields as $field ) {
		if ( $do_object ) {
			if ( isset( $term->$field ) ) {
				$term->$field = sanitize_term_field( $field, $term->$field, $term_id, $taxonomy, $context );
			}
		} else {
			if ( isset( $term[ $field ] ) ) {
				$term[ $field ] = sanitize_term_field( $field, $term[ $field ], $term_id, $taxonomy, $context );
			}
		}
	}

	if ( $do_object ) {
		$term->filter = $context;
	} else {
		$term['filter'] = $context;
	}

	return $term;
}

Changelog

Version Description
2.3.0 Introduced.