Search code examples
wordpresswp-list-categories

Display last child categories


I would print only the list child categories.

Example :

News --> Press Release --> Viking Cruises

I would print Viking Cruises

I have this code that works, but print the entire tree of categories not last.

<?php $categories = get_the_category();

      $separator = ' ';

      $output = '';

      if ( ! empty( $categories ) ) {

          foreach( $categories as $category ) {

              $output .= '<a href="' . esc_url( get_category_link( 
$category->term_id ) ) . '">' . esc_html ($category->name) . '</a>' . 
$separator;
          }

          echo trim( $output, $separator );

      } ?>   

thanks for help!


Solution

  • I have modified your code, Please try it. Hope it will work for you.

     <?php $categories = get_the_category();
         $separator = ' ';
         $output = '';
         if ( ! empty( $categories ) ) {
         foreach( $categories as $category ) {
          $children=get_categories(array( 'parent' => $category->cat_ID ));
              if ( count($children) == 0 ) {
                $output .= '<a href="' . esc_url( get_category_link( 
                $category->term_id ) ) . '">' . esc_html ($category->name) . 
               '</a>' . $separator;
             }
        }
    
             echo trim( $output, $separator );
    
      } ?>