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 = " / ";
}
?

Topic php categories Wordpress

Category Web


Only showing the child category

global $post;    
    $terms = wp_get_post_terms( $post->ID, 'product_cat' );
            foreach ( $terms as $term ) 
            {
                if($term->parent!=0)
                {
                    $pcategory = get_term( $term->parent, 'product_cat' );
                    $categories[] = $pcategory->slug;
                }
        }

Little change:

<?php $category_separator = "";
foreach((get_the_category()) as $childcat) {
     $parentcat = $childcat->term_id;
     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 = " / ";
}
?>

Actually you were getting the parent category id

 $parentcat = $childcat->category_parent;

Instead of that you need to get actual sub category id

$parentcat = $childcat->term_id;

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.