The standard WordPress function the_category() is great, but it has one flaw: it always generates HTML links (<a href="...">...</a>) to the archive page. What if you’re building a custom layout (like a portfolio card or slider) where the category should be plain text, not a clickable element?
The solution is to use get_the_category(), which returns an array of objects instead of ready-made HTML.
Code (snippet)
Here’s a ready-to-use snippet you can paste into your single.php or content.php:
<?php
// Get all categories assigned to the current post
$categories = get_the_category();
if ( ! empty( $categories ) ) {
// Display the name of the first category found
echo esc_html( $categories[0]->name );
}
?>
Displaying a comma-Separated list
If your post has multiple categories and you want to list them as comma-separated text:
<?php
$categories = get_the_category();
$output = array();
if ( ! empty( $categories ) ) {
foreach ( $categories as $category ) {
// Add name to the array
$output[] = esc_html( $category->name );
}
// Join the array into a string with a separator
echo implode( ', ', $output );
}
?>
Why get_the_category()?
This function gives you access to the full category object. Besides the name (->name), you can extract:
->slug(useful for CSS classes, e.g.,<span class="cat-<?php echo $cat->slug; ?>">)->term_id(category ID)->description(category description)->count(number of posts in this category)
Practical application
A common use case is styling labels on blog cards.
// Inside the WordPress loop
$cats = get_the_category();
$first_cat = !empty($cats) ? $cats[0] : null;
if ($first_cat) : ?>
<span class="badge badge-<?php echo esc_attr($first_cat->slug); ?>">
<?php echo esc_html($first_cat->name); ?>
</span>
<?php endif; ?>
This way, if you have a category “News”, you’ll get the class .badge-news, which you can easily color in CSS. This level of control is something the_category() simply doesn’t offer.



