get_term_children for immediate children only (not grandchildren)

Use the get_terms() function instead:

$term_children = get_terms(
    'mytaxname',
    array(
        'parent' => get_queried_object_id(),
    )
);

if ( ! is_wp_error( $terms ) ) {
    foreach ( $term_children as $child ) {
        echo '
            <div class="product-archive">
                <div class="post-title">
                    <h3 class="product-name"><a href="' . get_term_link( $child ) . '">' . $child->name . '</a></h3>
                </div>
            </div>
        ';
    }
}

get_terms() can return a WP_Error object, so you need to check that it didn’t. It returns an array of term objects, so you no longer need to retrieve the objects with get_term_by(). Since $child is a term object, get_term_link() doesn’t need the second parameter. get_terms() has more options for the second parameter. You should take a look.

Leave a Comment