0
votes

Need help : I must display only the child terms of a specific parent of a custom taxonomy WordPress, in my case: taxonomy name: "region", related to this: parent terms and their children: Europe: - Portugal; - Germany; - England;

Asia: - China; - Japan;

So for example I need to display in a list only the children of Europe, how can I do this? I tried a lot of methods and could only display all the children of all parents:

        <?php
        $taxonomyName = "region";
        //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>';
    ?>

But I need to display only for a specific parent. Thank you for your help

1

1 Answers

2
votes

You already have the answer. Just set your parent term and get rid of the top nested foreach.

 <?php
    $taxonomyName = "region";
    //Could use ACF or basic custom field to get the "parent tax ID" dynamically from a page. At least that's what I would do.
    $parent_tax_ID = '3';
    $parent_tax = get_term($parent_tax_ID);
    echo '<h3>' . $parent_tax->name . '</h3>';
    echo '<ul>';
    $terms = get_terms( $taxonomyName, array( 'parent' => $parent_tax_ID, 'orderby' => 'slug', 'hide_empty' => false ) );
    foreach ( $terms as $term ) {
        echo '<li><a href="' . get_term_link( $term ) . '">' . $term->name . '</a></li>';
    }
    echo '</ul>';
?>