term_is_ancestor_of()
云策文档标注
概述
term_is_ancestor_of() 函数用于检查一个分类法术语是否为另一个术语的祖先。它支持通过 ID 或对象作为参数,并递归验证层级关系。
关键要点
- 函数用途:判断 $term2 是否为 $term1 的子代术语,返回布尔值。
- 参数说明:$term1 和 $term2 可以是整数 ID 或术语对象,$taxonomy 指定所属分类法名称。
- 递归机制:如果 $term2 的直接父级不是 $term1,函数会递归检查父级链。
- 错误处理:当术语 ID 或父级信息缺失时返回 false。
代码示例
if ( term_is_ancestor_of( 4, get_queried_object_id(), 'sound' ) ) {
// 显示针对 Music 术语及其子术语的内容
wp_nav_menu( array( 'theme_location' => 'music-menu' ) );
}注意事项
- 确保 $taxonomy 参数正确,否则可能导致术语获取失败。
- 函数递归调用可能影响性能,建议在大型术语层级中谨慎使用。
- 相关函数:get_term() 用于获取术语数据,cat_is_ancestor_of() 为分类专用版本。
原文内容
Checks if a term is an ancestor of another term.
Description
You can use either an ID or the term object for both parameters.
Parameters
$term1int|objectrequired-
ID or object to check if this is the parent term.
$term2int|objectrequired-
The child term.
$taxonomystringrequired-
Taxonomy name that $term1 and
$term2belong to.
Source
function term_is_ancestor_of( $term1, $term2, $taxonomy ) {
if ( ! isset( $term1->term_id ) ) {
$term1 = get_term( $term1, $taxonomy );
}
if ( ! isset( $term2->parent ) ) {
$term2 = get_term( $term2, $taxonomy );
}
if ( empty( $term1->term_id ) || empty( $term2->parent ) ) {
return false;
}
if ( $term2->parent === $term1->term_id ) {
return true;
}
return term_is_ancestor_of( $term1, get_term( $term2->parent, $taxonomy ), $taxonomy );
}
Changelog
| Version | Description |
|---|---|
| 3.4.0 | Introduced. |
Skip to note 2 content
Codex
Use conditional tag to show different content based on term being displayed.
This example, placed in a theme’s taxonomy.php, uses Conditional Tags to show different content depending on the term being displayed. This is helpful when it is necessary to include something for any child term of a given term, instead of using taxonomy-$taxonomy-$slug.php method where you’d have to create taxonomy-$taxonomy-$slug.php files for each and every term.
The code snip below checks to see if the term called ‘Music’ (ID 4) for the taxonmy ‘Sound’ is being processed, and if so, presents a wp_nav_menu for the Music archive page, and any subterms of Music (e.g. jazz, classical.)
<div id="music_subnav_menu" class="subnav_menu"> 'Music' ) ); ?> </div>