A
A
Andrey2016-03-19 17:54:36
WordPress
Andrey, 2016-03-19 17:54:36

Show only child categories?

I found on the net such a code for displaying only child categories. Those. if the entry belongs to the category: Parent rubric - Child rubric, then only the Child rubric will be displayed. For example, Books - Detectives, then this code will display only a link to the child category Detectives.

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

The problem is that if the entry belongs to a category that does not have a child category, then nothing is displayed.
Please tell me how to modify this code so that if a post does not have a child category, then its Parent category is displayed, and not an empty space, as it is now. Thank you!

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question