How to only list the child terms of a taxonomy and not their parents?

I’m creating an age select menu in the admin, populated from a taxonomy of age. The taxonomy is hierarchical as follows:

  • 18-25 (parent, ID 183)
    • 18 (child)
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
  • 26-30 (parent, ID 184)
    • 26
    • 27
    • 28
    • 29
    • 30

I would like to only list the children (18, 19 etc) and not the parents (18-25, 26-30) etc. Currently I am using get_terms with the parent argument, but it doesn’t accept more than 1 parent ID. Here’s what I have so far, which shows the children from 18-25.

    $ages = get_terms( 'age', array(
        'hide_empty' => 0,
        'parent' => '183',
    ));

Here’s what I want it to do, but isn’t supported. I have also tried it with an array but it doesn’t work either.

    $ages = get_terms( 'age', array(
        'hide_empty' => 0,
        'parent' => '183,184',
    ));

I see there is a get_term_children function but I’m unsure of how to use this either as it looks like it only accepts one value also. Eg:
In this example it would build an unordered list but I could modify for select menu.

<?php
    $termID = 183;
    $taxonomyName = "age";
    $termchildren = get_term_children( $termID, $taxonomyName );

    echo '<ul>';
    foreach ($termchildren as $child) {
    $term = get_term_by( 'id', $child, $taxonomyName );
    echo '<li><a href="' . get_term_link( $term->name, $taxonomyName ) . '">' . $term->name . '</a></li>';
    }
    echo '</ul>';
?> 

5

This should work for you:

$taxonomyName = "age";
//This gets top layer terms only.  This is done by setting parent to 0.  
$parent_terms = get_terms( $taxonomyName, array( 'parent' => 0, 'orderby' => 'slug', 'hide_empty' => false ) );   
echo '<ul>';
foreach ( $parent_terms as $pterm ) {
    //Get the Child terms
    $terms = get_terms( $taxonomyName, array( 'parent' => $pterm->term_id, 'orderby' => 'slug', 'hide_empty' => false ) );
    foreach ( $terms as $term ) {
        echo '<li><a href="' . get_term_link( $term ) . '">' . $term->name . '</a></li>';   
    }
}
echo '</ul>';

Leave a Comment