cat_is_ancestor_of()
Checks if the specified category is a child of another specified category (all nesting levels are checked). Conditional tag.
Notes
-
This function will only work if the category specified in
$cat2is nested within category$cat1. -
The result will return
trueeven if $cat2 is nested in $cat1 through multiple categories (multi-level nesting check). - In parameters it is necessary to pass exactly number or object. For example if you pass a number as string
'4', the function will return false even if the categories are related.
Uses: term_is_ancestor_of()
1 time — 0.000757 sec (slow) | 50000 times — 1.05 sec (fast) | PHP 7.0.5, WP 4.5.1
No Hooks.
Returns
true|false. Whether $cat2 is child of $cat1.
Usage
cat_is_ancestor_of( $cat1, $cat2 );
- $cat1(number/object) (required)
- The ID of the parent category. The category that should be parent to the category specified in the
cat2parameter. - $cat2(number/object) (required).
- The ID of the child category of any level. The category which must be a child category to the category specified in the
$cat1parameter.
Examples
#1 Nav Menu only for category with ID 4
This is an example you can use on a category page to display a navigation menu wp_nav_menu() only for a category with ID 4 or categories nested within that category.
// if it is category 4 or its subcategory
if( cat_is_ancestor_of( 4, $cat ) || is_category( 4 ) ){
wp_nav_menu( [ 'menu' => 'Music' ] );
}
Changelog
| Since 2.1.0 | Introduced. |
cat_is_ancestor_of() cat is ancestor of code WP 6.8.3
function cat_is_ancestor_of( $cat1, $cat2 ) {
return term_is_ancestor_of( $cat1, $cat2, 'category' );
}