4

I want to get second level terms of a specific parent (first-level) term in a custom taxonomy. Sounds complicated but would be useful.

Term 1
   SubTerm-1.1
   SubTerm-1.2
       SubTerm-1.2.1
Term 2
   SubTerm-2.1

Say, if SubTerm->parent is Term 1's id, then i want to output SubTerm 1.1 and 1.2 but not 1.2.1.

wp_list_categories(array('depth' => 2, 'taxonomy' => 'customtax')); is not i'm looking for as it lists terms with their links, which i dont want to, and there is no filtering option by SubTerm->parent id.

So any idea?

5

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.

  • Parse error: syntax error, unexpected T_FUNCTION in this line: $second_level = array_filter($whole_tax, function ($t) { – Adige72 Jul 18 '12 at 8:27
  • @Adige72 What version of PHP are you using? (Inline functions were added in 5.3 I think.) – Richard Jul 18 '12 at 8:52
  • Hmm it's 5.2.6. I'll update and let you know. Thanks. – Adige72 Jul 18 '12 at 9:01
  • @Adige72 You could also defined a named function and pass its name, but the inline function is far more elegant (and adds the ability – via a use clause – to pass additional data from the caller): definition isn't separate and no global namespace pollution for a local problem. – Richard Jul 18 '12 at 11:09
-1
$tax ='taxonomy';
        $args = array(
          'taxonomy' => $tax,
          'hide_empty' => false,
          'parent' => 0,
          );
    $toplv_term_query = new WP_Term_Query($args);
        foreach($toplv_term_query->get_terms() as $toplv_term){
             $args = array(
               'taxonomy' => $tax,
               'hide_empty' => false,
               'parent' => $toplv_term->term_id,
              );
          $secondlv_term_query = new WP_Term_Query($args);
              foreach($secondlv_term_query->get_terms() as $secondlv_term){
                   $secondlv_term->term_id;

             }
        }
  • 1
    Please edit your answer, and add an explanation: why could that solve the problem? – fuxia Feb 27 '17 at 15:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.