How to display a list of categories

I’m trying to set up a list of categories with clickable links to that category.
I’ve looked at:

and am not quite sure where to put the code or how to access it on the page.

Read More

I understand the PHP well enough – it’s pretty straightforward, I’m just relatively new to WP and need some help implementing.

Related posts

3 comments

  1. 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

  2. As per the linked WPSE thread, and the accepted answer, the code is (copied & pasted):

    $categories =  get_categories('child_of=31');  
    foreach  ($categories as $category) {
        //Display the sub category information using $category values like $category->cat_name
        echo '<h2>'.$category->name.'</h2>';
        echo '<ul>';
    
        foreach (get_posts('cat='.$category->term_id) as $post) {
            setup_postdata( $post );
            echo '<li><a href="'.get_permalink($post->ID).'">'.get_the_title().'</a></li>';   
        }  
        echo '</ul>';
    }
    

    As for us (the WordPress developers) Codex is the key for most of the basics. So according to WordPress Codex:

    • get_categories() does query for all the categories of a site, and returns an array.
    • Similarly get_posts() does query for all the posts of a site, and returns an array.

    And they both are the shortcut of WP_Query(). You can get all their possible parameters from the Codex pages. As you are a PHP enthusiast, you know how the code is functioning: $categories is taking all the categories and for every category get_posts() is taking its posts.

    So it’s very similar to a mySQL query and a foreach loop in raw PHP. You can put this code into any of your WP site’s active theme’s template pages. Template Hierarchy can give you a detail insight.

    As per your title of the Question is:

    How to display a list of categories

    The answer can be:

    $categories =  get_categories();
    echo '<ul>';
    foreach  ($categories as $category) {
      echo '<li>'. $category->cat_name .'</li>';
    }
    echo '</ul>';
    

    am not quite sure where to put the code or how to access it on the page.

    I’ve already said, try putting the code into index.php, front-page.php, … anywhere. The key concept is: it’s just a SQL Query and a useful foreach loop of PHP.

  3. This method enables you to exclude any category simply by adding the cat i.d to the code.

    Here’s a better way to add a list of categories conditionally from your child themes functions file in any WordPress or theme specific hook location:

    add_filter( 'the_content', 'wpsites_list_cats' );
    function wpsites_list_cats($content) {
    if( is_singular('post') && is_main_query() ) {
    $args = array(
    'orderby' => 'name',
    'exclude' => '',
    'include' => '',
    'parent' => 0
    );
    $categories = get_categories( $args );
    echo'<nav id="primary-navigation" class="primary-navigation" role="navigation">';
    foreach ( $categories as $category ) {
    echo '<li><a href="' . get_category_link( $category->term_id ) . '">' .  $category->name . '</a></li>';
    }
    echo'</nav>';
    return $content;
        }
    }
    

    Here’s the result

    enter image description here

    And here’s the result if you want to use the existing styling from the Twenty Fourteens navigation menus which the above code includes.

    enter image description here

    The code also enables you to include specific categories or exclude any using the cat i.d’s

    You could also create a custom widget area and use the native WordPress category widget.

    Simply change the the_content hook to change the location of the categories list.

    Modified from this source

Comments are closed.