taxonomy_meta_box_sanitize_cb_input()
云策文档标注
概述
taxonomy_meta_box_sanitize_cb_input() 函数用于清理从输入式分类法元框(taxonomy metabox)提交的 POST 值。它处理原始术语数据,标准化分隔符,并返回清理后的术语数组,包括现有术语的 ID 或新术语的字符串。
关键要点
- 函数接受两个参数:$taxonomy(分类法名称,字符串,必需)和 $terms(原始术语数据,数组或字符串,必需)。
- 如果 $terms 是字符串,函数会基于本地化设置标准化分隔符为逗号,然后分割成数组。
- 函数遍历术语数组,跳过空值,使用 get_terms() 检查现有术语;如果找到,返回其 ID;否则,保留字符串以便创建新术语。
- 返回一个数组,包含清理后的术语(整数 ID 或字符串)。
代码示例
function taxonomy_meta_box_sanitize_cb_input( $taxonomy, $terms ) {
if ( ! is_array( $terms ) ) {
$comma = _x( ',', 'tag delimiter' );
if ( ',' !== $comma ) {
$terms = str_replace( $comma, ',', $terms );
}
$terms = explode( ',', trim( $terms, " ntr x0B," ) );
}
$clean_terms = array();
foreach ( $terms as $term ) {
if ( empty( $term ) ) {
continue;
}
$_term = get_terms(
array(
'taxonomy' => $taxonomy,
'name' => $term,
'fields' => 'ids',
'hide_empty' => false,
)
);
if ( ! empty( $_term ) ) {
$clean_terms[] = (int) $_term[0];
} else {
$clean_terms[] = $term;
}
}
return $clean_terms;
}注意事项
- 函数自 WordPress 5.1.0 版本引入。
- 依赖 get_terms() 和 _x() 函数,确保在相关上下文中可用。
- 处理时考虑多语言分隔符,使用 _x() 获取本地化逗号字符。
原文内容
Sanitizes POST values from an input taxonomy metabox.
Parameters
$taxonomystringrequired-
The taxonomy name.
$termsarray|stringrequired-
Raw term data from the
'tax_input'field.
Source
function taxonomy_meta_box_sanitize_cb_input( $taxonomy, $terms ) {
/*
* Assume that a 'tax_input' string is a comma-separated list of term names.
* Some languages may use a character other than a comma as a delimiter, so we standardize on
* commas before parsing the list.
*/
if ( ! is_array( $terms ) ) {
$comma = _x( ',', 'tag delimiter' );
if ( ',' !== $comma ) {
$terms = str_replace( $comma, ',', $terms );
}
$terms = explode( ',', trim( $terms, " ntrx0B," ) );
}
$clean_terms = array();
foreach ( $terms as $term ) {
// Empty terms are invalid input.
if ( empty( $term ) ) {
continue;
}
$_term = get_terms(
array(
'taxonomy' => $taxonomy,
'name' => $term,
'fields' => 'ids',
'hide_empty' => false,
)
);
if ( ! empty( $_term ) ) {
$clean_terms[] = (int) $_term[0];
} else {
// No existing term was found, so pass the string. A new term will be created.
$clean_terms[] = $term;
}
}
return $clean_terms;
}
Changelog
| Version | Description |
|---|---|
| 5.1.0 | Introduced. |