Display only one result from “get_the_category_list”

I’d like get_the_category_list to only display one or two categories instead of all the categories associated with the post. Haven’t been able to find any results.

<?php echo get_the_category_list(); ?>

Any help would be appreciated

Related posts

Leave a Reply

4 comments

  1. $categories = get_the_category();
    if ( ! empty( $categories ) ) {
        echo '<a href="' . esc_url( get_category_link( $categories[0]->term_id ) ) . '">' . esc_html( $categories[0]->name ) . '</a>';
    }
    
  2. Quick idea would be to pass some simple separator like comma and cut from the start of result till it.

    But I think that if you want better control on output it would make more sense to use level deeper get_the_category() function and build markup yourself.

  3. If you want to limit get_the_category to any number you can use break;

    For example if you want to limit echoing a category + link to show say only 5 categories.

         $i = 0;
          foreach((get_the_category()) as $cat) {
            echo '<a href="'.get_category_link($cat->cat_ID).'"> | ' . $cat->cat_name . '</a>';
            if (++$i == 5) break;
          }