You can check the category 'parent'
arribute, and if is 0
the category is a parent one.
I’ve also noted some things on your code:
- When the is is passed
get_the_category
is unused, but it is called anyway - You use
get_the_category
assuming function are called in the loop, but there is no check for that - If, for any case,
get_the_category
return no categories, your function thrown errors - Before inserting retrieved values inside html shoul be escaperd with
esc_*
functions
I rewrote your function considering all those things and adding the check for parent category:
function thb_DisplaySingleCategory($boxed = true, $id = false) {
if ( (int) $id ) {
$cat = get_category($id);
if ( ! empty($cat) ) {
$backup = $cat->term_id;
if ( $cat->parent == 0 ) $id = $cat->term_id;
}
}
if ( empty($id) && in_the_loop() ) {
$id = '';
$categories = get_the_category();
if ( empty( $categories ) ) return;
while ( empty($id) && ! empty($categories) ) {
$cat = array_shift($categories);
if ( $cat->parent == 0 ) $id = $cat->term_id;
}
}
// if no parent cat found, but a not-parent cat id passed to function use that
if ( ! (int) $id && isset($backup) ) $id = $backup;
if ( ! (int) $id ) return;
$name = get_cat_name($id);
$url = esc_url( get_category_link($id) );
$wcolor = $boxed ? 'background' : 'color';
$class = $boxed ? ' class="boxed"' : '';
$color = GetCategoryColor($id);
$frmt="<a href="https://wordpress.stackexchange.com/questions/119997/%s"%s title="https://wordpress.stackexchange.com/questions/119997/%s" style="%s:%s;">%s</a>";
return sprintf( $frmt, $url, $class, esc_attr($name), $wcolor, $color, esc_html($name) );
}