cat_is_ancestor_of( int|object $cat1, int|object $cat2 ): bool

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

VersionDescription
2.1.0Introduced.

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.)

    <?php 
      // if the category is music or a music SUBcategory, 
      if (cat_is_ancestor_of(4, $cat) or is_category(4)):  ?>
      <div id="music_subnav_menu" class="subnav_menu">
        <?php wp_nav_menu( array('menu' => 'Music' )); ?>
      </div>
    <?php endif; ?>

You must log in before being able to contribute a note or feedback.