• Skip to main content
  • What We Do
  • Our Work
  • Contact

Mackey

December 27, 2014 by Mackey

WordPress taxonomy / term if category is parent of child

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
}

Filed Under: Code Snippets

Reader Interactions

Comments

  1. Mike says

    May 4, 2020 at 3:55 pm

    Thank you so much for this handy snippet. I needed exactly something like this. Works perfect for my use case.

  2. Gagan says

    May 28, 2020 at 2:57 am

    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

Mackey Creative Lab
Web Design and Development, Branding, Graphic Design and Marketing Strategy
680 East Colorado Blvd., Suite 180 & Second Floor, Pasadena, CA 91101
info@mackeycreativelab.com // 626 214 5093
© 2014-2021 Mackey, LLC, All Rights Reserved

Want to join the Lab? Become a lab partner

Need Wordpress Performance & Security Management? Learn More