get_the_category() WordPress Function

The get_the_category() function is used to get the category of the current post.

get_the_category( int $post_id = false ) #

Retrieves post categories.


Description

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().


Top ↑

Parameters

$post_id

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

Default value: false


Top ↑

Return

(WP_Term[]) Array of WP_Term objects, one for each category assigned to the post.


Top ↑

Source

File: wp-includes/category-template.php

function get_the_category( $post_id = false ) {
	$categories = get_the_terms( $post_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 ] );
	}

	/**
	 * Filters the array of categories to return for a post.
	 *
	 * @since 3.1.0
	 * @since 4.4.0 Added `$post_id` parameter.
	 *
	 * @param WP_Term[] $categories An array of categories to return for the post.
	 * @param int|false $post_id    ID of the post.
	 */
	return apply_filters( 'get_the_categories', $categories, $post_id );
}


Top ↑

Changelog

Changelog
VersionDescription
0.71Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.