Scroll to top

How to get only first category name in single.php

I was working on a project and need to show only the name of first category assigned to a post. The below code helped me achieve that quickly.

$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>';
}
Share Post:
Author avatar
Zahid Iqbal
I am a web designer and developer working full-time.

Post a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.