'How to show the related categories on sidebar on the category/posts page using php

I have a quote website and it has almost 50 categories, with parent child relationship.

enter image description here

What I want is when I open love quote page, on the sidebar it will show related categories list to love quotes (child categories i.e boyfriend wishes, cute love quote). And when I go to any child category page (i.e boyfriend quote) it will show related child categories under that parent one, and so on with all other categories.

Shortly, I want same scenario as related posts works but I want it with categories list. I think I can do this with dynamic code that I put in the sidebar.

Currently I use this code on sidebar widget:

<?php
if (is_category()) {
    $cat = get_query_var('cat');
    $this_category = get_category($cat);
    $this_category = wp_list_categories('hide_empty=0&hierarchical=true&orderby=id&show_count=0&title_li=&use_desc_for_title=1&child_of='.$this_category->cat_ID."&echo=0");
    if($this_category !='<li>No categories</li>')
    {
     echo '<h3>Products</h3>'; 
     echo '<ul>'.$this_category.'</ul>'; 
    }
}
?>

There is problem with this one. It shows all sub categories on main parent category page, but when I open any sub category page it shows nothing on sidebar (it means it is only getting sub category on prent page).

What I want is to show related categories list depending on current category.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source