Site icon Hip-Hop Website Design and Development

Showing Subcategory’s Name and Link Instead of Parent Category’s

Right now my code is displaying the category name and link. But if an article is in a subcategory, I want to display the subcategory’s name and link instead of the parent category’s name and link. For some reason though it’s still just showing the parent category. Any ideas what I’m doing wrong with the code?

    <?php $category_separator = "";
foreach((get_the_category()) as $childcat) {
     $parentcat = $childcat->category_parent;
     if( $parentcat != 0 ) echo '<span class="' . get_cat_name($parentcat) .'"><a href="' . get_category_link($parentcat) . '">' .get_cat_name($parentcat) .'</a></span>';
     else echo '' . $category_separator . '<span class="'. $childcat->cat_name .'"><a href="' . get_category_link($childcat) .'">' . $childcat->cat_name . '</a></span>';
    $category_separator = " / ";
}
?>