All you have to do is to track if you already echoed some category and add a comma in such case:
function get_level($category, $level = 0) {
if ($category->parent == 0) {
return $level;
}
$category = get_term( $category->parent );
return get_level( $category, $level + 1 );
}
function display_cat_level( $level = 0, $link = false) {
$cats = get_the_terms( null, 'category' );
$echoed = 0;
if ( $cats ) {
foreach ( $cats as $cat ) {
$current_cat_level = get_level( $cat );
if ( $current_cat_level == $level ) {
if ( $echoed ) {
echo ', ';
}
if ( true == $link ) {
echo '<a href="' . get_term_link( $cat->term_id ) . '">' . esc_html( $cat->name ) . "</a>";
} else {
echo esc_html( $cat->name );
}
$echoed++;
}
}
}
}
PS. I’ve also simplified your get_level
function a little bit and added some html escaping in display_cat_level
.