How to create custom tag cloud in WordPress
Posted by: Nuwan Sameera Hettiarachchi on: July 23rd, 2010
In: Tips and IT,WordPress Comments!

Previous article was about some new features in wordpress 3.0. But today I like to write small Hack in WordPress template. You know, there is a grate feature Tag cloud which is displays a list of tags has been assigned to posts. WordPress Tags can be generated by wp_tag_cloud() API function by passing relevant arguments. Using this method you can show list of tags somewhere in you template (ex: sidebar).

Since Version 2.8, the taxonomy parameter was added so that any taxonomy could be used to generate the tag clouds. As well as WordPress contain existing widget so that easily add tag cloud to the sidebar or somewhere in template.

The clouds are available for Categories or any other Custom Taxonomies to present in you web site. But you can control only available parameters for appearance tag cloud.

But if you want to present the post count for a specific tag, we cannot generate using wp_tag_cloud() function. So we can use simply following Hack to generate any type of output in your tag cloud.

   $args = array('taxonomy'  => 'post_tags' );
   $tags = get_terms( $args['taxonomy'], array_merge( $args, array( 'orderby' => 'count', 'order' => 'DESC' ) ) ); // Always query top tags
 
   if (!empty( $tags )) {
	foreach ($tags as $tag){
          $link = get_term_link( intval($tag->term_id), $args['taxonomy'] );						
           $list .= '<li><strong class="tag_link"><a href="'.$link.'">'.$tag->name.'</a> ('.$tag->count.')</strong></li>';
	}
   }
echo $list;

The get_terms() function will fetch the all tags data as an array for specific taxonomy. Above example I used default post_tags as taxonomy. But get_terms() function doesn’t contain the tags link, so I used get_term_link() inside of the Foreach loop. Well, finally print the output as follows,

  • http://www.thikbro.com/blog/ Isuranga

    Hm… Thanks for this Post. I got it and it helped me to do my work.

  • Luke S.

    I tried this but had received an error on line 7. Do you have any ideas?