Highlight the current post’s tags using CSS

The idea is to show all the tags used on the site and then add a CSS class to the tags that are used in the current post. This class can then be styled as required. In this example, the active class is added to the current post’s tags.

In this example, the post-tags are shown in a list using the <li> tag, but this can be changed to any HTML.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
// Get all tags in the site excluding the ones that are not used for any post
$allTags = get_terms( 'post_tag', 'hide_empty=1' );

// Get the tags of the current post
$currentPostTags = get_the_tags(get_the_ID());

// run through each tag in $allTags
foreach($allTags as $tag=>$tagVal){
    // build a list of all tags and add class 'active' to tags that are in $currentPostTags
    $tagList.='<li'.(((in_array($tagVal, $currentPostTags)))?' class="active"':'').'><a href="'.get_term_link($tagVal->term_id).'">'.$tagVal->name.'</a></li>';
}

// print the list
echo '<ul>'.$tagList.'</ul>';

Note: In Line 5, it is assumed that get_the_ID() will return the current post’s ID because this code is run within the WordPress Loop. If it is not, this should be replaced with another way to get the current post’s ID.