Displaying Child Category & Taxonomy Term

In general, if you assign a parent and a child category to a post. Your regular the_category function should display both the child and parent category. However, there are ways to display the child category or taxonomy term in WordPress. This could particularly be very useful if you want to display post on parent category archive page. In this post I will explain how it works in WordPress. This method should work for for both the WordPress Categories and for Custom Taxonomy.

For Categories

The following snippet should work with your "Posts" section in WP. All you need to do is to place the following snippet on your single.php or archive.php page. Ideally, this snippet should work inside any standard WordPress Loop.
$categories = get_the_category($post_id);
   foreach ($categories as $category) {
   if (($category->category_parent) !== 0) {
      echo '<a href="'.get_category_link($category->cat_ID).'">';
      echo $category->name.'</a>';} }
At the very beginning of this snippet, I assigned a variable ($categories) to hold all the categories assigned to any specific post (based on post ID) using the get_the_category function. Then I ran a foreach loop. The initial loop should have given every single category assigned to the post. However, since our goal was to find only the child category, I checked it with a if condition. So, it should only display the categories that has a parent category or in other word, if the parent category value is not equal to zero. I also generated the hyperlink for categories using get_category_link function which I think could be useful as well.

For Taxonomies

Custom taxonomy is a great way to organize your Custom Post Type. Just in case, if you don't know how to register custom taxonomy in WP, here is a post that I wrote way back. Feel free to check it out. Following snippet should display the child term of a parent term. The logical procedure is pretty much the same as before. We just simply change some functions to get around.
$terms = get_the_terms($post->ID, 'category');
   foreach ($terms as $term) {
   if (($term->parent) !== 0) {
      echo '<a href="'.get_term_link($term->slug, $term->taxonomy).'">';
      echo $term->name.'</a>'; } }
First of all, to grab all the terms assigned to a post, I used get_the_terms function. Like before, I ran a foreach loop and checked if the term has any parent term. In order to populate the link for the term I used get_term_link function. Note: For Taxonomy part, you must mention the registered taxonomy name at the very beginning of the the line. Replace the "category" with with your desired taxonomy.
$terms = get_the_terms($post->ID, 'category');
The reason why I used "category" word is to show you that this snippet works even for the native posts categories. It also should work with your custom taxonomy without any hiccup. Try it out and let me know. Now, I am taking questions.


Commenting is disabled.