I have a blog with 1 parent category and 3 child subcategories. For technical reasons, in the backoffice, when I write an article, I have to check the parent AND the child category.

In every article, I want to display the name of its "direct" category, and not the parent. Here's what I do in my template :

In my template, I'm displaying category of an article like this (I need the slug in the link class !) :

<?php foreach((get_the_category()) as $category) { 
echo '<a class="tag-cat ' . $category->slug . '" href="' . get_category_link($category->cat_ID) . '">' . $category->cat_name . '</a>'; } ?>

So, is there a way to only display the direct (child) category ? And not the parent ?

Thanks in advance for your help ! :)


If you know the parent category name, then you could just do an if inside the foreach

Demo code

foreach((get_the_category()) as $category) {
 if($category->cat_name!="parent category name")    { 
  echo '<a class="tag-cat ' . $category->slug . '" href="' . get_category_link($category->cat_ID) . '">' . $category->cat_name . '</a>';
} ?>


Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.