2

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

4 Answers 4

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

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.

2

This worked. Found in http://codex.wordpress.org/Function_Reference/get_the_category

<?php
$category = get_the_category(); 
echo $category[0]->cat_name;
?>
1

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

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.