categories - Wordpress display only child category in template

admin2025-01-07  4

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 ?

Share Improve this question edited Mar 2, 2023 at 8:27 YourManDan 4342 silver badges12 bronze badges asked Aug 10, 2018 at 8:33 HelloooHellooo 31 bronze badge 1
  • Possible duplicate of Display only deepest category on a single post? – Jacob Peattie Commented Aug 10, 2018 at 8:45
Add a comment  | 

1 Answer 1

Reset to default 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>';
 } 
} ?>

?>

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1736263199a871.html

最新回复(0)