I’ve recently been doing a lot of design work with WordPress and in particular it’s use of taxonomies. Here’s a great snippet I picked up over at WordPress for Beginners that allows you to display the child taxonomy of another taxonomy.

Begin by opening up your custom taxonomy template file from wp-content>themes>YOUR-THEME-NAME. It may be named something like: taxonomy-{taxonomyname}.php. Paste the following code where ever you want to display the list.

$term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) );
if ($term->parent == 0) {
&title_li=&child_of=' . $term->term_id);
} else {
&title_li=&child_of=' . $term->parent);

Now replace YOUR-TAXONOMY-NAME with the name of your custom defined taxonomy.

How It Works:

Using get_term_by we query the information about the current taxonomy by slug. For example: if your taxonomy is called Macs and you are on a page /Macs/mac-book-pros/ then $term variable will pull all the data related to the specific term page that you are on.

The above snippet assumes a hierarchical layout to the taxonomies and uses a conditional $term->parent variable. This variable outputs the ID of the parent taxonomy. If you are on the parent taxonomy Macs the $term->parent will echo 0 ($term->parent == 0). Wp_list_categories() is then used to display terms from the custom taxonomy that are child_of the term whose page you are on ($term->term_id).

Because the $term->parent no longer equals 0 any child taxonomy page is blank. $term->parent is outputting the ID of the parent category. To fix this we run an else statement using wp_list_categories() function except $term->term_id is changed to $term->parent.

Tagged with: