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() .
Parameters
$post_id
intoptional- The post ID. Defaults to current post ID.
Default:
false
Source
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 the `$post_id` parameter.
*
* @param WP_Term[] $categories An array of categories to return for the post.
* @param int|false $post_id The post ID.
*/
return apply_filters( 'get_the_categories', $categories, $post_id );
}
Hooks
- apply_filters( ‘get_the_categories’,
WP_Term[] $categories ,int|false $post_id ) Filters the array of categories to return for a post.
Changelog
Version | Description |
---|---|
0.71 | Introduced. |
Show the First Category Name Only
(Echoes the first array element ([0]) of
$categories
.)Make the first category link to the category page:
Get the post category if you have a custom post_type
Example response from function:
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.Get the Post Categories From Outside the Loop
To display a list of categories associated with a post, separated by commas, write this code:
$cats = array();
foreach (get_the_category($post_id) as $c) {
$cat = get_category($c);
array_push($cats, $cat->name);
}
if (sizeOf($cats) > 0) {
$post_categories = implode(', ', $cats);
} else {
$post_categories = 'Not Assigned';
}
echo $post_categories;
Display all categories with name and description
Show list of categories with comma
Show Category Images
This outputs category images named after the
cat_ID
with the alt attribute set tocat_name
. You can also use any of the other member variables instead.