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, displays the Parent and Child categories used for each post in the following format (colon after the parent and hyphen after each child apart from the last).
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
I've worked on the exact same case a few months ago and here is my solution
Tested and hope this help.
I have done something similar for showing in Rest Api, so all this does is arranges all of the categories into hierarchical arrays/objects. And it only works for first-grade children.
So the result will be something like:
Hope this helps someone...