'List all categories on single template, add active class to category attached to post

On my single post template, I need to list all the categories and also add an active class to the category associated to the post.

This is the closest I've seen but returns no active class:

            $term    = get_queried_object();
            $term_id = ( isset( $term->term_id ) ) ? (int) $term->term_id : 0;
            $categories = get_categories( array(
                'taxonomy'   => 'category', 
                'orderby'    => 'name',
                'parent'     => 0,
                'hide_empty' => 0, 
            ) );
            ?>

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

                    $cat_class = ( $cat_ID == $term_id ) ? 'active' : ''; ?>
                    <li><a href="<?php echo home_url() ?>/category/<?php echo $category->slug ?>" class="<?php echo $cat_class; ?>"><?php echo  $category_name; ?></a></li>

             <?php endforeach; ?>

            </ul> ''''

I've also tried wp_list_categories(); with the same result. $term_id returns "0" which is where I suspect my problem lies since it doesn't match the category id. Original code from here



Solution 1:[1]

I think what you need is has_category($category, $post) function, which returns true if your post has the category given.

$category can be the category id or name and $post can be the post id or object.

Check the Wordpress codex

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 סטנלי גרונן