Show current linked top level parent category and linked sub categories on post and categories

Created the following by combining various examples on SO and elsewhere to show the current top level category and first level subcategories if you are on a post or category page.

<?php
$cat = get_query_var(‘cat’);
$cat_title = get_the_category_by_ID($cat);
$cat_link = get_term_link($cat); ?>
<ul class=”side-list”>
<li><a class=”side-list-title” href=”<?php echo $cat_link ?>”><?php echo $cat_title ?></a></li>
<?php
$cat_list = wp_list_categories(‘child_of=’.$cat.’&hide_empty=1&title_li=&echo=0′);
if($cat_list) {
echo ‘<ul>’;
echo $cat_list;
echo ‘</ul>’;
}
?>
</ul>

It works perfectly when viewing a top level category page, but tried viewing on a single page and shows a white screen. Assuming, “$cat = get_query_var(‘cat’);” must only work on category pages is their another method to get the current top level category id? Also doesn’t work on sub level category page, but also presumably because the above isn’t finding the top level category id.

There are many posts about finding the top level id, but most all appear to result in “Array”. For instance this: https://stackoverflow.com/questions/15190163/echo-top-most-parent-ancestor-category-of-a-post

Read more here:: Show current linked top level parent category and linked sub categories on post and categories

Leave a Reply

Your email address will not be published. Required fields are marked *