WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] get_terms to display only direct children (2 posts)

  1. Leandro Dimitrio
    Member
    Posted 1 year ago #

    Hello there!

    I'm trying to have get_terms to display only direct children of an specific term, but that doesn't seem to be working.

    <?php
                    $current_term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) );
                    $taxonomy_name = 'product_category';
                    $termchildren = get_terms($taxonomy_name,array('child_of' => $current_term->term_id));
                    ?>
                    <ul>
                    <?php
                    foreach ( $termchildren as $child ) {
                        $term = get_term_by( 'id', $child, $taxonomy_name );
                        $image = z_taxonomy_image_url($term->term_id);
                        //var_dump($term);?>
                        <li>
                            <a href="<?php echo get_term_link($term->slug, $taxonomy_name); ?>"><img src="<?php if ($image) { echo $image; } else { echo get_bloginfo('template_directory') . '/images/placeholder.png'; } ?>" alt="<?php echo $term->name;?>"/></a>
                            <a href="<?php echo get_term_link( $term->slug, $taxonomy_name );?>"><?php echo $term->name;?></a>
                        </li>
                    <?php } ?>
                    </ul>

    This code displays ALL children.

    Anyone have a clue?

    Thanks in advance!

  2. Leandro Dimitrio
    Member
    Posted 1 year ago #

    Got it!

    Managed to do it by setting both "child_of" and "parent" to $term_id.

    $termchildren = get_terms($taxonomy_name,array('child_of'=>$current_term->term_id,'parent' => $current_term->term_id));

    Cheers!

Topic Closed

This topic has been closed to new replies.

About this Topic