Display Only One Category

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

Read More

I want it to be Category One…

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

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

Related posts

Leave a Reply

1 comment

  1. 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