Grouping Parent and child categories for post and displaying

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

– Travel
– World
– Business


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;

$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



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

Leave a Reply

Your email address will not be published. Required fields are marked *