0

right now this code is showing an article's subcategories if it has one. But it's also showing the parent category too (so both the parent category and child categories show up simultaneously). Is there a way to modify this code so that if an article is in a subcategory, it only shows those subcategories and hides the parent category? And if it's only in a parent category, it shows the parent category? Thank you!

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

1 Answer 1

1

Once you can't know the order of categories returned by get_the_category, I suggest to loop through the categories and fill two arrays, one for parent and one for children. After that if the parents array is empty showing the children, otherwise show the parents:

$categories = get_the_category();
if ( ! empty($categories) ) {
  $parents = array();
  $children = array();
  foreach( get_the_category() as $cat ) {
    if ( $cat->parent == 0 ) {
      $parents[] = $cat;
    } else {
      $children[] = $cat;
    }
  }
  $toshow = ! empty($children) ? $children : $parents;
  $sep = '';
  if ( ! empty($toshow) ) { foreach( $toshow as $cat ) {
    echo $sep;
    echo '<span class="' . $cat->name .'">';
    echo '<a href="' . get_category_link($cat->term_id) . '">' . $cat->name . '</a></span>';
    $sep = ' / ';
  } }
}
4
  • This doesn't seem to be working for me...
    – Jon
    Oct 16, 2013 at 4:35
  • Thank you, but now it seems to be showing only the parent category and not the child category. ^_^;; Posts that are in a parent category show those categories, but if it's in a child category of a parent category, only the parent category shows.
    – Jon
    Oct 16, 2013 at 18:23
  • Oh, no, I want it so that if a post has child categories to only show those child categories and not the parent categories.
    – Jon
    Oct 16, 2013 at 18:34
  • @user1445975 Now if a post has parent + children categories show only children categories. If a post has only children categories show children categories. If a post has only parent categories show parent categories.
    – gmazzap
    Oct 16, 2013 at 18:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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