Using WordPress ‘get_category()’ PHP function

The get_category() WordPress PHP function retrieves category data given a category ID or category object.

Usage

To use the function, pass the category ID or object as a parameter:

$category_data = get_category( $category_id );

Parameters

  • $category (int|object): Required. Category ID or category row object.
  • $output (string): Optional. 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): Optional. How to sanitize category fields. Default: ‘raw’.

More information

See WordPress Developer Resources: get_category()

Examples

Get category data by ID

Get the category data for a category with an ID of 15 and store it in a variable:

$category_data = get_category(15);

Check if a category has posts

Check if a category with the given ID has at least one post:

if (get_category($id)->category_count > 0) {
    // Do something
}

Get current category data on a category template

Retrieve the current category data in a category template:

$current_category = get_category(get_query_var('cat'), false);

Get category data as an associative array

Get category data as an associative array instead of the default WP_Term object:

$category_data = get_category(15, ARRAY_A);

Get category data with sanitized fields

Get category data with sanitized fields:

$category_data = get_category(15, OBJECT, 'display');