How to Display Child Taxonomy on Parent Taxonomy’s Archive Page
In the past we have shown you how to display subcategories on category pages in WordPress. Recently while working with Custom Taxonomies, we found a need to display child-taxonomies on parent-taxonomies archive page. After doing a bit of research, we didn’t find a single tutorial covering this issue. In this article, we will show you how to display a list of child taxonomies on taxonomies pages.
Open up your custom taxonomy template file which may look like: taxonomy-{taxonomyname}.php and paste the following code where ever you want to display the list:
<?php $term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) ); if ($term->parent == 0) { wp_list_categories('taxonomy=YOUR-TAXONOMY-NAME&depth=1&show_count=0 &title_li=&child_of=' . $term->term_id); } else { wp_list_categories('taxonomy=YOUR-TAXONOMY-NAME&show_count=0 &title_li=&child_of=' . $term->parent); } ?>
Don’t forget to replace YOUR-TAXONOMY-NAME with the name of your taxonomy.
Final Result:
Explanation:
We are using get_term_by to query the information of the current taxonomy by slug. For example if your taxonomy is called topics and you are on a page /topics/nutrition/ then $term variable will pull all the data related to the specific term page that you are on.
In the project we were working on, the topics taxonomy was hierarchical just like categories. So we decided to run a conditional using $term->parent variable. This variable outputs the ID of the parent taxonomy. So if you are on the taxonomy nutrition which is the parent taxonomy, then $term->parent will echo 0. This is why we said if $term->parent == 0 then use wp_list_categories() function to display terms from our custom taxonomy that are child_of the term which page you are on. We accomplished this by using $term->term_id as the child_of variable.
Now if you go to the child taxonomy page, it would have been blank because the $term->parent would no longer equals to 0. On a child taxonomy page, $term->parent outputs the ID of the parent category. So we ran an else statement using the same wp_list_categories() function except we changed $term->term_id to $term->parent.
There you have it. We hope that this helps everyone who was looking for a solution.