get_term_children for immediate children only (not grandchildren)

I want to display term children of a custom taxonomy. Currently, I am able to do this using get_term_children, but using this, it displays children and grandchildren, I want to avoid this and make that only immediate children are shown.

This is what I have right now ( but it outputs children and grandchildren) :

<?php
$term_id = get_queried_object_id();
$taxonomy_name="mytaxname";

$termchildren = get_term_children( $term_id, $taxonomy_name );

foreach ( $termchildren as $child ) {
    $term = get_term_by( 'id', $child, $taxonomy_name );
    echo ' <div class="product-archive">';
        echo '<div class="post-title">
      <h3 class="product-name"><a href="' .get_term_link( $term, $taxonomy_name ). '">' .$term->name. '</a></h3>  
    </div>
  </div>';  }
?>

This is what I am trying to get to work so it shows only immediate children:

<?php
$term_id = get_queried_object_id(); 
$taxonomy_name="mytaxname";

$args = array('parent' => $term_id,'parent' => $term_id );
$termchildren = get_terms( $taxonomy_name, $args);

foreach ( $termchildren as $child ) {
    $term = get_term_by( 'id', $child, $taxonomy_name );
    echo ' <div class="product-archive">';
        echo '<div class="post-title">
      <h3 class="product-name"><a href="' .get_term_link( $term, $taxonomy_name ). '">' .$term->name. '</a></h3>  
    </div>
  </div>';  }
?>

This gives me a error :

Catchable fatal error: Object of class WP_Error could not be converted to string in…

What did I do wrong?

Thanks!

1
1

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