Using WordPress ‘cat_is_ancestor_of()’ PHP function

The cat_is_ancestor_of() WordPress PHP function checks if a category is an ancestor of another category.

Usage

Here’s a basic example of how to use the function, including a custom example showing input and output.

// Check if category with ID 4 is an ancestor of the current category
if (cat_is_ancestor_of(4, $cat)) {
    // Show some content only for child categories of category 4
    echo '<div id="music_subnav_menu" class="subnav_menu">';
    wp_nav_menu( array('menu' => 'Music' ));
    echo '</div>';
}

Parameters

  • $cat1 (int|object): Required. This could be the ID or the category object. This is the potential parent category you’re checking.
  • $cat2 (int|object): Required. This is the child category. It could be the ID or the category object.

More information

See WordPress Developer Resources: cat_is_ancestor_of()

This function is implemented in WordPress and is not deprecated as of the last update to this guide.

Examples

Check if Category 10 is an Ancestor of the Current Category

if (cat_is_ancestor_of(10, $cat)) {
    echo 'This category is a child of category 10!';
}

Check if ‘News’ Category is an Ancestor of ‘Local News’ Category

$news = get_category_by_slug('news');
$local_news = get_category_by_slug('local-news');

if (cat_is_ancestor_of($news, $local_news)) {
    echo 'Local News is a child category of News!';
}

Using the Function in a Loop

$categories = get_categories();

foreach ($categories as $category) {
    if (cat_is_ancestor_of(4, $category)) {
        echo $category->name . ' is a child of category 4!';
    }
}

Display a Specific Menu for Child Categories

if (cat_is_ancestor_of(4, $cat)) {
    wp_nav_menu( array('menu' => 'Special Menu for Category 4 Children') );
}

Customizing the Page Based on Parent Category

if (cat_is_ancestor_of(4, $cat)) {
    get_template_part('category-4-child');
} else {
    get_template_part('category');
}

In this example, if the category is a child of category 4, a specific template part (‘category-4-child’) is loaded. If not, the default category template part is loaded.