Highlight Current Tag in wp_tag_cloud

I’m in the middle of building a website and one of the pages will be a glossary. The first page of the glossary will display a list of all the words, which are custom post types assigned into a custom taxonomy called “letter” which pulls the first letter of the word.

On top of the glossary, there is a “navigation” which is a a wp_tag_cloud of all the letters (A-Z). The user can then click into the letter, and the page displays all of the words that start with that letter.

The question I have is that if there is a way I can add a current-tag styling to the tag that I’m currently viewing.

My code for this so far is this:

  <!-- Glossary Search -->
  <div class="search-container">
    <div class="container">
      <div class="show-search col-lg-8 col-lg-offset-3">
       <form role="search" method="get" id="searchform" action="<?php echo home_url( "https://wordpress.stackexchange.com/" ); ?>">
          <div class="letter-list row-fluid">  


           <!-- IMPORTANT --> <?php wp_tag_cloud( array( 'taxonomy' => 'letter', 'format' => 'flat', 'hide_empty' => false) ); ?>


            <input type="text" value="Search the Glossary" onblur="if (this.value == '') {this.value="Search the Glossary";}" onfocus="if (this.value == 'Search the Glossary') {this.value="";}" name="s" id="glossarySearch" />
          </div>
      </form>
      </div> <!-- end shows-search -->
    </div> <!-- end container -->
  </div> <!-- end search-container -->

Thanks so much for your help!

2 Answers
2

When you are in a tag template, a body class is added with term-{termID}, so you can hook in “wp_generate_tag_cloud_data” to check if class is present and add custom class to the tag 😉

 function tribalpixel_tag_cloud_class_active($tags_data) {

        $body_class = get_body_class();

        foreach ($tags_data as $key => $tag) {
            if(in_array('term-'.$tag['id'], $body_class)) {
                $tags_data[$key]['class'] =  $tags_data[$key]['class'] ." active-tag";
            } 
        }
        return $tags_data;
    }

    add_filter('wp_generate_tag_cloud_data', 'tribalpixel_tag_cloud_class_active');

after that you simply use CSS to style 😉

Leave a Comment