I have this function that displays the specified hierarchy level category of a post. For example <?php display_cat_level(0,true); ?>
will display the top/parent category, while <?php display_cat_level(2,true); ?>
will display the second child category.
If the post has more than one category in any given level then the categories will be displayed inline with no spaces or commas between them like this cat1acat1bcat1c
instead of cat1a, cat1b, cat1c
. How would I update the function to comma separate multiple categories displayed?
function get_level($category, $level = 0)
{
if ($category->parent == 0) {
return $level;
} else {
$level++;
$category = get_term( $category->parent );
return get_level($category, $level);
}
}
function display_cat_level( $level = 0 , $link=false){
$cats = get_the_terms( null, 'category' );
if( $cats ){
foreach($cats as $cat){
$current_cat_level = get_level($cat);
if( $current_cat_level == $level ){
if($link==true) {
echo '<a href="'.get_term_link( $cat->term_id ).'">'.$cat->name."</a>";
} else {
echo $cat->name."";
}
}
}
}
}