How to Display Only Parent Category in your WordPress Post Loop


When you use the_category() template function in your WordPress theme, it displays both the parent category and any child/subcategories under it. If you are creating a site that uses a lot of child categories to categorize the content, then this can become a problem because the_category code will create a lot of clutter. For example, it will show as “Filed in Blogs, Genesis Framework, 2 Column Theme etc”. Unfortunately the_category() does not have any optional parameters like child=0 or depth=-1. When creating our WordPress Gallery, this was one of the issues we had to deal with. In this article, we will show you how to display only parent category in your WordPress post loop.

Simply open your single.php file or anywhere else that you want to utilize this code, and then replace the following code or something similar to it:

<?php the_category(', '); ?>

with this code:

<?php $parentscategory ="";  foreach((get_the_category()) as $category) {  if ($category->category_parent == 0) {  $parentscategory .= ' <a href="' . get_category_link($category->cat_ID) . '" title="' . $category->name . '">' . $category->name . '</a>, ';  }  }  echo substr($parentscategory,0,-2); ?>

Now this will let you display only the parent category in your WordPress post loop. For example see the image in the example:

Display Only Parent Category in Your WordPress Loop

Our issue with the gallery was not so much clutter, but rather it was to make sure our Site Submission Form powered by Gravity Forms can capture all the data and store it as a Post Draft, so it can make our editors job a lot easier. Unfortunately, Gravity Forms does not support Custom Taxonomy because it would have saved us the trouble, but due to the lack of that feature, we had to use the code above. Each of our gallery articles have two categories associated with it (Parent Category: Genre of Site, and Child Category: Theme Framework it uses). In our next article, we will share how you can display only Child Category in your WordPress Post Loop. Stay updated, and make sure you submit your WordPress site to our WordPress Gallery.



Seraphinite AcceleratorOptimized by Seraphinite Accelerator
Turns on site high speed to be attractive for people and search engines.