get_the_category ( int $id = false )

Retrieve post categories.

This tag may be used outside The Loop by passing a post id as the parameter.

Note: This function only returns results from the default “category” taxonomy. For custom taxonomies use get_the_terms().

Return: (array) Array of objects, one for each category assigned to the post.

Source file: wp-includes/category-template.php

View source


Parameters

$id

(int) (Optional) default to current post ID. The post ID.

Default value: false



Source

function get_the_category( $id = false ) {
	$categories = get_the_terms( $id, 'category' );
	if ( ! $categories || is_wp_error( $categories ) )
		$categories = array();

	$categories = array_values( $categories );

	foreach ( array_keys( $categories ) as $key ) {
		_make_cat_compat( $categories[$key] );
	}

	/**
	 * Filter the array of categories to return for a post.
	 *
	 * @since 3.1.0
	 *
	 * @param array $categories An array of categories to return for the post.
	 */
	return apply_filters( 'get_the_categories', $categories );
}


Changelog

  • Since: WordPress 0.71

User Contributed Notes

  1. Show All Categories as Links
    This outputs all the categories assigned to the post as links. Must be used inside the loop. You can also use the function get_the_category_list() for this.

    $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 );
    }
    
  2. Show Category Images
    This outputs category images named after the cat_ID with the alt attribute set to cat_name. You can also use any of the other member variables instead.

    <?php
    $categories = get_the_category();
    foreach ( $categories as $category ) { 
    	echo '<img src="' . esc_url( 'http://example.com/images/' . intval( $category->term_id ) . '.jpg' ) . '" alt="' . esc_attr( $category->name ) . '" />'; 
    }
    
  3. Show the First Category Name Only

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

    (Echoes the first array element ([0]) of $categories.)

    Make the first category 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>';
    }
    
  4. Get the Post Categories From Outside the Loop

    <?php
    $post = get_post();
    if ( $post ) {
    	$categories = get_the_category( $post->ID );
    	var_dump( $categories );
    }
    

You must log in before being able to contribute a note.