arrow_back
Back

WordPress categories in templates: get_categories and get_the_category

Andrew Dorokhov Andrew Dorokhov schedule 1 min read
menu_book Table of Contents

All categories of the site

$categories = get_categories();

Every element is an object with the following properties:

if ( $categories ) {
    foreach ( $categories as $cat ) {

        // $cat->term_id
        // $cat->name                  (Category 1)
        // $cat->slug                  (category-1)
        // $cat->term_group            (0)
        // $cat->term_taxonomy_id      (4)
        // $cat->taxonomy              (category)
        // $cat->description           (Description text)
        // $cat->parent                (0)
        // $cat->count                 (14)
        // $cat->object_id             (2743)
        // $cat->cat_ID                (4)
        // $cat->category_count        (14)
        // $cat->category_description  (Description text)
        // $cat->cat_name              (Category 1)
        // $cat->category_nicename     (category-1)
        // $cat->category_parent       (0)
    }
}

Categories of the current post

Inside the loop, get_the_category() returns the categories of the post being rendered:

$categories = [];

foreach ( get_the_category() as $category ) {
    $categories[] = $category->name;
}

$categories_list = implode( ', ', $categories );

To get the same list already formatted as links, use get_the_category_list():

get_the_category_list( $separator, $parents, $post_id );

// Example:
$categories_list = get_the_category_list( ', ' );

Categories are just one taxonomy — see taxonomies and terms for registering your own and for querying posts by term.

code

Need Help with Development?

Happy to help — reach out via the contacts or go straight to my Upwork profile.

work View Upwork Profile arrow_forward
Next Article

WordPress navigation menus: register_nav_menu and wp_nav_menu

arrow_forward