Get second level terms of custom taxonomy

You can use PHP’s array_filter to process the results of a taxonomy query function that returns its results, and then display them. Something like:

# This returns the whole taxonomy...
$whole_tax = get_terms('customtax', array('hide_empty' => 0));
$second_level = array_filter($whole_tax, function ($t) {
  # This term has a parent, but its parent does not.
  return $t->parent != 0 && get_term($t->parent, 'customtax')->parent == 0;
});

At this point you can render $second_level to output in whatever format you want.

NB. If this is often used on a busy side should avoid all those extra get_term calls by reading from the $whole_tax array assuming the documentation’s statement that get_term always hits the database when passed an id.

Leave a Comment