3

On my WordPress theme, it displays all of the categories a post is in on the homepage for the post block, I only want to display one category even if a post is under multiple categories.

i.e. Category One, Category Two, Category Three

I want it to be Category One...

This is the code that is in place at the moment:

<h2><?php the_category(', ') ?></h2>

1 Answer 1

9

Here's snippet to display first category from post.

$category = get_the_category();

if ( $category[0] ) {
    echo '<h2><a href="' . get_category_link( $category[0]->term_id ) . '">' . $category[0]->cat_name . '</a></h2>';
}

Original idea of the code is from WordPress Codex

2
  • When using this snippet of code, it doesn't simply any categories. It's simply blank. Commented Feb 6, 2012 at 9:26
  • Are using it inside the loop? Otherwise you need pass post ID into get_the_category()
    – Mamaduka
    Commented Feb 6, 2012 at 10:24

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.