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 !) :
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 ?
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 !) :
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 ?
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>';
}
} ?>
?>