0

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 ! :)

0

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

Demo code

<?php
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 agree to our terms of service, privacy policy and cookie policy

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