Using WordPress ‘get_the_category()’ PHP function

The get_the_category() WordPress PHP function retrieves the categories associated with a post.

Usage

get_the_category($post_id);

Input:

  • $post_id (integer): The post ID. Defaults to the current post ID.

Output:

  • An array of category objects.

Parameters

  • $post_id (int): Optional. The post ID. Defaults to current post ID.

More information

See WordPress Developer Resources: get_the_category()

Examples

Display First Category Name

This example retrieves the categories for a post and displays the first category name:

$categories = get_the_category();
if (!empty($categories)) {
    echo esc_html($categories[0]->name);
}

This example retrieves the categories for a post and displays the first category as a link to the category page:

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

Display Categories for Custom Post Type

This example retrieves the categories for a custom post type:

$categories = get_the_terms($post->ID, 'taxonomy');
foreach ($categories as $category) {
    echo $category->term_id . ', ' . $category->slug . ', ' . $category->name . '<br />';
}

Display Category Information

This example retrieves the categories for a post and prints the category information:

$categories = get_the_category();
var_dump($categories);

This example retrieves the categories for a post and displays all categories as links:

$categories = get_the_category();
$separator = ' ';
$output = '';
if (!empty($categories)) {
    foreach ($categories as $category) {
        $output .= '<a href="' . esc_url(get_category_link($category->term_id)) . '" alt="' . esc_attr(sprintf(__('View all posts in %s', 'textdomain'), $category->name)) . '">' . esc_html($category->name) . '</a>' . $separator;
    }
    echo trim($output, $separator);
}