Here is code snippet from WordPress that display the categories (or terms from other taxonomies) assigned to a post ordered by parent-child category relationship.This example must be used inside the loop.
$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;
}
Information on this page may help you to adjust the code to your requirements.
I hope this will help.