Family Encyclopedia >> Electronics

How to display child taxonomy on parent taxonomy 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 the parent taxonomies archive page. After doing some research, we did not find a single tutorial on this topic. In this article, we'll show you how to display a list of child taxonomies on taxonomy pages.

Open your custom taxonomy template file which may look like:taxonomy- taxonomyname .php and paste the following code wherever you want to display the list:

 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.

End result:

How to display child taxonomy on parent taxonomy archive page

Explanation:

We are using get_term_by To consult the information of the current taxonomy by bullet. For example, if your taxonomy is named topics and it's on a page /topics/nutrition/ then the variable $term will pull all the data related to the specific term page it's on.

In the project we were working on, the topic taxonomy was hierarchical, as were the categories. So we decided to run a conditional using $term->main variable. This variable generates the ID of the main taxonomy. So if you're in the nutrition taxonomy, which is the parent taxonomy, then $term->parent will echo 0. That's why we said if $term->parent ==0 then use the wp_list_categories() function to display terms from our custom taxonomy that are children of the term what page are you on. We achieve 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 $term->parent would no longer be equal to 0. On a child taxonomy page, $term->parent produces the ID of the parent category. So we execute an else statement using the same wp_list_categories() function, except we change $term->term_id to $term->parent.

There you go. We hope this helps everyone who was looking for a solution.