A quick little WordPress snippet to determine if a category or taxonomy or term has a parent, has a parent and child, or has no parent, but a child.
Specifically we used this to show and hide sub-categories via a drop down menu using Woocommerce, but could be handy in many instances. Just insert this code where you are want to add conditional logic based on the category structure.
$term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) ); // get current term $parent = get_term($term->parent, get_query_var('taxonomy') ); // get parent term $children = get_term_children($term->term_id, get_query_var('taxonomy')); // get children if(($parent->term_id!="" && sizeof($children)>0)) { // has parent and child }elseif(($parent->term_id!="") && (sizeof($children)==0)) { // has parent, no child }elseif(($parent->term_id=="") && (sizeof($children)>0)) { // no parent, has child }
Mike says
Thank you so much for this handy snippet. I needed exactly something like this. Works perfect for my use case.
Gagan says
Thanks for this code mate
can you please explore more this code, i want to display all categories name with active terms name
hope you understand