0

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

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;
1
  • Thanks, but for some reason it still shows the parent category too. Is there a way to hide the parent if the article is part of a child category? – Jon Oct 13 '13 at 20:33
0

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;
                }
        }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.