WordPress at Your Fingertips

cat_is_ancestor_of() WP 2.1.0

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 $cat2 is nested within category $cat1.

  • The result will return true even 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.
1 time — 0.000757 sec (slow) | 50000 times — 1.05 sec (fast) | PHP 7.0.5, WP 4.5.1

No Hooks.

Return

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 cat2 parameter.
$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 $cat1 parameter.

Examples

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.

Code of cat_is_ancestor_of() WP 5.8.1

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

Relations (of posts terms...)

Conditional tags (all)

Categories

No comments
    Log In