Display the categories (or terms from other taxonomies) assigned to a
post ordered by parent-child category relationship. Similar to the
function get_the_category_list() which orders the categories by name.
This example must be used inside the loop.
<?php
$taxonomy = 'category';
// Get the term IDs assigned to post.
$post_terms = wp_get_object_terms(
$post->ID,
$taxonomy,
array(
'fields' => 'ids'
)
);
// Separator between links.
$separator=", ";
if ( ! empty( $post_terms ) && ! is_wp_error( $post_terms ) ) {
$term_ids = implode( ',' , $post_terms );
$terms = wp_list_categories( array(
'title_li' => '',
'style' => 'none',
'echo' => false,
'taxonomy' => $taxonomy,
'include' => $term_ids
) );
$terms = rtrim( trim( str_replace( '<br />', $separator, $terms ) ), $separator );
// Display post categories.
echo $terms;
}
Source: user contributed example from the Developer’s Code Reference.