get_the_category()
Gets an array of categories data related to current post.
The function can be used outside of the WordPress loop by passing the post ID.
Use get_the_terms(), to get terms from another taxonomy (not "category").
Hooks from the function
Return
WP_Term[]
. Array of WP_Term objects, one for each category assigned to the post.
Each WP_Term object is also augmented with properties generated by _make_cat_compat().
Usage
get_the_category( $post_id );
- $post_id(int)
- The post ID.
Default: current post ID
Examples
#1 First category name
Show only the name of the first category (if the post belongs to one or more categories):
$cats = get_the_category(); echo array_shift( $cats )->name;
#2 Function Response Example
$categories = get_the_category(); print_r( $categories );
Result:
#3 Get first category data from the array
Show the First Category Name Only.
In this example we get first array element ([0]) of $categories.
$categories = get_the_category(); if ( ! empty( $categories ) ) { echo esc_html( $categories[0]->name ); }
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 Post categories outside the loop
An example of how to get post categories outside the WordPress Loop:
global $post; $categories = get_the_category( $post->ID );
The data that each category object contains (see all properties in class WP_Term and function _make_cat_compat()):
$cat = get_the_category($post->ID); //category ID $cat->term_id //category name $cat->name // Category Label $cat->slug // Category description (set on the category editing page) $cat->description // ID of parent category $cat->parent // Number of records in the category $cat->count
#5 Output links to the post's categories
foreach ( get_the_category() as $category ) { printf( '<a href="%s" class="link link-text">%s</a>', esc_url( get_category_link( $category ) ), esc_html( $category->name ) ); }
#6 Comma-separated links to the post's categories
$links = array_map( function ( $category ) { return sprintf( '<a href="%s" class="link link-text">%s</a>', esc_url( get_category_link( $category ) ), esc_html( $category->name ) ); }, get_the_category() ); echo implode( ', ', $links );
#7 Let's show an image for each category
This example shows how you can create an image for each category, the alt attribute will show the name of the category. The images must have the same names as the category IDs (12.jpg) and must be located in the root of the site in the images folder. The code must be used inside the WP Loop:
foreach( get_the_category() as $category ){ echo '<img src="http://example.com/images/' . $category->term_id . '.jpg" alt="' . $category->name . '" />'; }
Changelog
Since 0.71 | Introduced. |