WordPress Query Taxonomy for Child and Parent

This was a code experiment to display parent or child taxonomy terms relative to the current post.

I have a taxonomy-types.php set up with a custom post type (Products) and on this page I want to display different content depending on what level (hierarchical) taxonomy is currently being displayed, which are like this;

  • Cushion
    • Colours
      • Blue
      • Red
    • Themes
      • Children’s
      • Seaside
  • Curtain
    • Colours
      • Purple
      • Orance

I have 3 levels of taxonomy (above) and I need to test whether the current taxonomy:

  1. Has no parent but has a child (level 1)
  2. Has both a parent and a child (level 2)
  3. Has a parent and no child (level 3)

This will give me the three different levels. Depending on what level the visitor is currently in, I’ll display something different on the page.

$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

Hire WordPress Experts at Codeable.

The only WordPress exclusive freelancer platform that connects thousands of customers with the top WordPress freelance experts to work on projects of any size. 

Free estimate • No obligation to hire • 100% risk-free