I have seen a few questions for how to display parent and child categories but can’t seem to find a solution for what I am doing.

I’m using the default wordpress post with several categories and child categories for an example I have

News
– Travel
– World
– Business

Article
-General

Case Study
-Thomas Cook
– Easy Jet

The post can have any number of categories but what I am looking to do is group the child with its parent so that when I display a post it for example a News post with the Travel and World sub catergories it would look like this

News: Travel – World

Currently I am using the following code;

<?php 
$categories = get_the_category();
$separator = ' - ';
$output = '';
if ( ! empty( $categories ) ) {
    foreach( $categories as $category ) {
        $output .= '<a class="blog-panel-cat" href="' . esc_url( get_category_link( $category->term_id ) ) . '" alt="' . esc_attr( sprintf( __( 'View all posts in %s', 'textdomain' ), $category->name ) ) . '">' . esc_html( $category->name ) . '</a>' . $separator;
    }
    echo trim( $output );
}
?>

But his just outputs one category after the other with no way of grouping so I can add ‘:’ after the parent and separate the child for that parent with ‘-‘ and also a double space before the next parent.

Any help appreciated

Thanks

Ian

Read more here: Grouping Parent and child categories for post and displaying


Solution:

If you know the solution of this issue, please leave us a reply in Comment section, to update the question.


Wordpress related questions and answers: