is_object_in_term()
云策文档标注
概述
is_object_in_term() 函数用于检查指定对象是否与给定术语相关联。它支持通过 term_id、名称或 slug 进行匹配,并处理输入验证和缓存优化。
关键要点
- 函数检查对象是否与任何给定术语关联,匹配方式包括 term_id、名称和 slug。
- 参数包括 $object_id(对象ID)、$taxonomy(分类法名称)和可选的 $terms(术语ID、名称、slug 或数组)。
- 返回布尔值或 WP_Error,错误时返回 WP_Error。
- 内部使用缓存机制(如 get_object_term_cache 和 wp_cache_set)提升性能。
- 如果 $terms 为空,则检查对象是否在给定分类法中有任何术语。
代码示例
if ( is_object_in_term( $post->ID, 'custom_taxonomy_name', 'term_name' ) ) :
echo 'YES';
else :
echo 'NO';
endif;
原文内容
Determines if the given object is associated with any of the given terms.
Description
The given terms are checked against the object’s terms’ term_ids, names and slugs.
Terms given as integers will only be checked against the object’s terms’ term_ids.
If no terms are given, determines if object is associated with any terms in the given taxonomy.
Parameters
$object_idintrequired-
ID of the object (post ID, link ID, …).
$taxonomystringrequired-
Single taxonomy name.
$termsint|string|int[]|string[]optional-
Term ID, name, slug, or array of such to check against.
Default:
null
Source
function is_object_in_term( $object_id, $taxonomy, $terms = null ) {
$object_id = (int) $object_id;
if ( ! $object_id ) {
return new WP_Error( 'invalid_object', __( 'Invalid object ID.' ) );
}
$object_terms = get_object_term_cache( $object_id, $taxonomy );
if ( false === $object_terms ) {
$object_terms = wp_get_object_terms( $object_id, $taxonomy, array( 'update_term_meta_cache' => false ) );
if ( is_wp_error( $object_terms ) ) {
return $object_terms;
}
wp_cache_set( $object_id, wp_list_pluck( $object_terms, 'term_id' ), "{$taxonomy}_relationships" );
}
if ( is_wp_error( $object_terms ) ) {
return $object_terms;
}
if ( empty( $object_terms ) ) {
return false;
}
if ( empty( $terms ) ) {
return true;
}
$terms = (array) $terms;
$ints = array_filter( $terms, 'is_int' );
if ( $ints ) {
$strs = array_diff( $terms, $ints );
} else {
$strs =& $terms;
}
foreach ( $object_terms as $object_term ) {
// If term is an int, check against term_ids only.
if ( $ints && in_array( $object_term->term_id, $ints, true ) ) {
return true;
}
if ( $strs ) {
// Only check numeric strings against term_id, to avoid false matches due to type juggling.
$numeric_strs = array_map( 'intval', array_filter( $strs, 'is_numeric' ) );
if ( in_array( $object_term->term_id, $numeric_strs, true ) ) {
return true;
}
if ( in_array( $object_term->name, $strs, true ) ) {
return true;
}
if ( in_array( $object_term->slug, $strs, true ) ) {
return true;
}
}
}
return false;
}
Changelog
| Version | Description |
|---|---|
| 2.7.0 | Introduced. |
Skip to note 2 content
Codex
Example
ID, 'custom_taxonomy_name', 'term_name' ) ) : echo 'YES'; else : echo 'NO'; endif; ?>