Verify if a category is the child of another category

Is there a way to verify if a category is child of another category? For example if I have clothes category and in that category I have t-shirts as sub-category. To do something like: is parent category clothes? Yes, so display text. I hope that you understand me. Thanks in advance!

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Yes, there are two functions you can use:

For the default category taxonomy, you can use cat_is_ancestor_of():

// Retrieve category object by slug:
$parent_cat = get_category_by_slug( 'clothes' );  // term object
$child_cat  = get_category_by_slug( 't-shirts' ); // term object

/* Or retrieve category ID by name:
$parent_cat = get_cat_ID( 'Clothes' );  // term ID
$child_cat  = get_cat_ID( 'T-Shirts' ); // term ID
*/

if ( cat_is_ancestor_of( $parent_cat, $child_cat ) ) {
    echo 't-shirts is child of clothes';
}

For custom taxonomies, you would use term_is_ancestor_of():

// Set the custom taxonomy's slug:
$taxonomy = 'my_taxonomy';

// Retrieve term object by slug:
$parent_cat = get_term_by( 'slug', 'clothes', $taxonomy );
$child_cat  = get_term_by( 'slug', 't-shirts', $taxonomy );
/* Or name, if you want:
$parent_cat = get_term_by( 'name', 'Clothes', $taxonomy );
$child_cat  = get_term_by( 'name', 'T-Shirts', $taxonomy );
*/

if ( term_is_ancestor_of( $parent_cat, $child_cat, $taxonomy ) ) {
    echo 't-shirts is child of clothes';
}

And note that cat_is_ancestor_of() is really a wrapper around (i.e. it uses) term_is_ancestor_of() which accepts either term ID or object, so for examples, you could do cat_is_ancestor_of( 1, 2 ) and term_is_ancestor_of( 3, 4, 'my_taxonomy' ) whereby the numbers like 1 and 3 are term IDs.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x