Get child terms of current term of the current post

I think you should rather use get_queried_object() to return the current page’s term. From there you should get the taxonomy name, term ID and the parent.

Now here is my logic on this. Whenever you are on a parent term, ie. music or videos, the parent will return 0. You can use this to execute the code only if you are on a parent term page.

Here is the output from var_dump($cat_terms); on a child page

array(0) {
}

and here is from a parent page

array(2) {
  [0]=>
  int(119)
  [1]=>
  int(120)
}

119 and 120 is the child terms of my parent term

You have the taxonomy name and term ID, so you can use get_term_children to get the child terms from your terms music or videos. Like I said, you would only want to do this on the parent page. But that is all up to you.

Here is the code

<?php 
    $queried_object = get_queried_object('term');
        $tax = $queried_object->taxonomy;
        $term = $queried_object->term_id;
        $parent = $queried_object->parent;

    if( 0 == $parent ) {
        $cat_terms = get_term_children( $term, $tax );
         ?>
           <pre><?php var_dump($cat_terms); ?></pre>
         <?php 
        //<---DO SOMETHING ON PARENT TERM PAGE--->
    }else{
        //<---DO SOMETHING ON CHILD TERM PAGE
    }
?>

Leave a Comment