函数文档

cat_is_ancestor_of()

💡 云策文档标注

概述

cat_is_ancestor_of() 函数用于检查一个分类是否是另一个分类的祖先。它基于 term_is_ancestor_of() 实现,专门针对 WordPress 的分类(category)术语。

关键要点

  • 函数接受两个参数:$cat1 和 $cat2,可以是整数 ID 或分类对象,用于检查 $cat2 是否是 $cat1 的子分类。
  • 返回值是布尔值,True 表示 $cat2 是 $cat1 的子孙分类(包括任何层级),False 表示不是。
  • 参数必须是整数或对象类型;如果传递字符串形式的整数,函数将返回 False。
  • 该函数在 WordPress 2.1.0 版本中引入,是 term_is_ancestor_of() 的包装函数,专门用于分类术语。

代码示例

if ( cat_is_ancestor_of( 4, get_queried_object_id() ) ) {
    // 如果当前分类是 ID 为 4 的分类的子分类,则执行操作
    wp_nav_menu( array( 'theme_location' => 'music-menu' ) );
}

注意事项

  • 确保参数类型正确,避免因传递字符串导致函数返回 False。
  • 该函数仅适用于分类(category),其他术语类型应使用 term_is_ancestor_of()。

📄 原文内容

Checks if a category is an ancestor of another category.

Description

You can use either an ID or the category object for both parameters.
If you use an integer, the category will be retrieved.

Parameters

$cat1int|objectrequired
ID or object to check if this is the parent category.
$cat2int|objectrequired
The child category.

Return

bool Whether $cat2 is child of $cat1.

More Information

  • The function evaluates if the second category is a child of the first category.
  • Any level of ancestry will return True.
  • Arguments should be either integer or objects; if arguments are string representations of integers and not true integers, cat_is_ancestor_of will return False.

Source

function cat_is_ancestor_of( $cat1, $cat2 ) {
	return term_is_ancestor_of( $cat1, $cat2, 'category' );
}

Changelog

Version Description
2.1.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    Basic Example

    This example, placed in a theme’s archive.php, uses Conditional Tags to show different content depending on the category being displayed. This is helpful when it is necessary to include something for any child category of a given category, instead of using category-slug.php method where you’d have to create category-slug.php files for each and every category.

    The code snip below checks to see if the category called ‘Music’ (ID 4) is being processed, and if so, presents a wp_nav_menu for the Music archive page, and any subcategories of Music (e.g. jazz, classical.)

    
      <div id="music_subnav_menu" class="subnav_menu">
         'Music' )); ?>
      </div>