1

The code below works for my posts from Custom Post Type(called Sermon) which is displaying the child category name only with its links.

<?php
  $categories = get_the_category();
  if ( ! empty( $categories ) ) {
  echo '<a href="' . esc_url( get_category_link( $categories[0]->term_id ) ) . '">Child Category : ' . esc_html( $categories[0]->name ) . '</a>';
  }
?>

But it doesn't work when I reuse it for my posts from post type itself(News category). It keeps showing the parent category(News), unless I unchecked it so it displays the child category only(like entertainment, politics, etc.).

Any help would be appreciated. Thanks!

Randy
  • 319
  • 3
  • 13
  • `print_r($categories)` chk this – devpro Oct 11 '16 at 07:30
  • I have tried changing the object names but it really keeps showing the parent tag on some posts. I hope someone could help me create a function for this one if this is not achievable without using custom function. :) – Randy Oct 11 '16 at 07:58

1 Answers1

0

I've solved my problem with this custom function I found online and modified a little bit to meet my requirements.

function the_category_children($slug=""){
  $separator = ', ';
  $output = '';
  if($categories       = get_the_category()):
    if($slug_category   = get_category_by_slug($slug)):
      foreach($categories as $category):
        if (cat_is_ancestor_of($slug_category, $category)):
          $output .= '<a href="' . esc_url( get_category_link( $category->term_id ) ) . '">' . esc_html( $category->name ) . '</a>' . $separator;
        endif;
      endforeach;
      echo trim( $output, $separator );
    endif;
  endif;
}

And calling this function the_category_children('category_name') inside the loop(content.php). ^_^

Randy
  • 319
  • 3
  • 13