Question

I am trying to display the grand child terms for a custom taxonomy term.

The main parent taxonomy term is product_range, the child taxonomy term is Mechanical Trackballs, each child category has multiple grand child terms for example:

Product Ranges > Mechanical Trackballs > 16mm

Product Ranges > Mechanical Trackballs > 25mm

I am trying to list all the grand child items for the child taxonomy term.

I currently have the following code:

$term_id = 49;
$taxonomy_name = 'product_range';
$term_children = get_term_children( $term_id, $taxonomy_name );
echo '<ul>';
   foreach ( $term_children as $child ) {
     $term = get_term_by( 'id', $child, $taxonomy_name );
       echo '<li><a href="' . get_term_link( $child, $taxonomy_name ) . '">' . $term->name . '</a></li>';
   }
echo '</ul>';

However as you can see I have to add the child taxonomy terms ID in each time I want to display its child items and this isn't future proof as this is for a clients site and they may add/remove taxonomy terms.

How can I display the grand child taxonomy terms for each child term without having to declare the taxonomy term ID?

Was it helpful?

Solution

I managed to answer this question myself by adding get_queried_object()->term_id; instead of the taxonomy terms ID. It now outputs all the grandchild taxonomy terms for the current taxonomy term.

Here is my updated working code:

$term_id = get_queried_object()->term_id;
$taxonomy_name = 'product_range';
$term_children = get_term_children( $term_id, $taxonomy_name );
echo '<ul>';
foreach ( $term_children as $child ) {
$term = get_term_by( 'id', $child, $taxonomy_name );
echo '<li><a href="' . get_term_link( $child, $taxonomy_name ) . '">' . $term->name . '</a></li>';
}
echo '</ul>';
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top