You could use get_ancestors()
. You can transform this:
<a href="#" class="<?php $category = get_category($cat);
echo $category->category_nicename;?>"><?php single_cat_title('') ?></a>
Into this (I don’t know what $cat
is as you have not shown it in your question, I assume it is a category ID, if not, you have to provide category ID):
<?php
$cat_ancestors = get_ancestors( $cat, 'category' );
$top_parent = get_category( end( $cat_ancestors ) );
?>
<a href="#" class="<?php esc_attr_e( $top_parent->slug );?>"><?php echo $top_parent->name; ?></a>
To make the code works also if the category is already the top parent category, you need to check the value returned by get_ancestors
. For example:
<?php
$cat_ancestors = get_ancestors( $cat, 'category' );
if( !empty($cat_ancestors) ) {
$cat = get_category( end( $cat_ancestors ) );
} else {
$cat = get_category( $cat );
}
?>
<a href="#" class="<?php esc_attr_e( $cat->slug );?>"><?php echo $cat->name; ?></a>