How to display a list of categories

I will show you how to display a list of categories in WordPress and also mark the active category, see code below:

<?php
// Get the current queried object
$term    = get_queried_object();
$term_id = ( isset( $term->term_id ) ) ? (int) $term->term_id : 0;

$categories = get_categories( array(
    'taxonomy'   => 'category', // Taxonomy to retrieve terms for. We want 'category'. Note that this parameter is default to 'category', so you can omit it
    'orderby'    => 'name',
    'parent'     => 0,
    'hide_empty' => 0, // change to 1 to hide categores not having a single post
) );
?>

<ul>
    <?php
    foreach ( $categories as $category ) 
    {
        $cat_ID        = (int) $category->term_id;
        $category_name = $category->name;

        // When viewing a particular category, give it an [active] class
        $cat_class = ( $cat_ID == $term_id ) ? 'active' : 'not-active';

        // I don't like showing the [uncategoirzed] category
        if ( strtolower( $category_name ) != 'uncategorized' )
        {
            printf( '%3$s',
                esc_attr( $cat_class ),
                esc_url( get_category_link( $category->term_id ) ),
                esc_html( $category->name )
            );
        }
    }
    ?>
</ul>

Notes about the code above:

get_queried_object() retrieve the currently-queried object. For example:

  • if you’re on a single post, it will return the post object
  • if you’re on a page, it will return the page object
  • if you’re on an archive page, it will return the post type object
  • if you’re on a category archive, it will return the category object
  • if you’re on an author archive, it will return the author object
  • etc.

But there are some implications when using get_queried_object(), you should not expect it to return a post type object even when is_post_type_archive() is true. Check it out for more info.

Also, note that get_queried_object() is a wrapper for $wp_query->get_queried_object(), so it returns a WP object data type.

get_categories()

get_categories() retrieve list of category objects. Currently accepts only one parameter – $args. The $args parameter specifies a list of arguments that should be used to retrieve categories. See get_terms() for additional options.

However, to get the category for a particular posts here’s a simple function I wrote: How to get list of categories for a post

Leave a Comment

error code: 523