get_category()
Retrieves category data given a category ID or category object.
If you pass the $category parameter an object, which is assumed to be the category row object retrieved the database. It will cache the category data.
If you pass $category an integer of the category ID, then that category will be retrieved from the database, if it isn't already cached, and pass it back.
If you look at get_term(), then both types will be passed through several filters and finally sanitized based on the $filter parameter value.
No Hooks.
Return
Object|Array|WP_Error|null
. Category data in type defined by $output parameter. WP_Error if $category is empty, null if it does not exist.
Usage
get_category( $category, $output, $filter );
- $category(int|object) (required)
- Category ID or category row object.
- $output(string)
- The required return type. One of OBJECT, ARRAY_A, or ARRAY_N, which correspond to a WP_Term object, an associative array, or a numeric array, respectively.
Default: OBJECT - $filter(string)
- How to sanitize category fields.
Default: 'raw'
Examples
#1 Display the data of the category whose page we are on (the current one):
$cat = get_category( get_query_var('cat') ); // OR if( is_category() ){ $cat = get_category( get_queried_object() ); } print_r( $cat );
As a result, we will see something like this:
stdClass Object ( [term_id] => 85 [name] => Category Name [slug] => category-name [term_group] => 0 [term_taxonomy_id] => 85 [taxonomy] => category [description] => [parent] => 70 [count] => 0 [cat_ID] => 85 [category_count] => 0 [category_description] => [cat_name] => Category Name [category_nicename] => category-name [category_parent] => 70 )
Now we can get category data like so:
echo $cat->name; echo $cat->slug; echo $cat->count; // etc...
Changelog
Since 1.5.1 | Introduced. |
get_category() get category code WP 6.7.1
function get_category( $category, $output = OBJECT, $filter = 'raw' ) { $category = get_term( $category, 'category', $output, $filter ); if ( is_wp_error( $category ) ) { return $category; } _make_cat_compat( $category ); return $category; }