Extending the WordPress Tag Cloud

In a recent project, I made use of the built in WordPress Tag Cloud widget. The default widget gives you only a few options, none of which I found quite useful.

The project relied on the ability to be able to browse entries by tags and as a visual cue, I wanted to style the currently active tag. Most active list items that WordPress generates are conveniently tagged with a class identifier such as active or current. Unfortunately the Tag Cloud omits this feature.

Extending wp_tag_cloud(), here is a snippet that can be added to your theme’s functions.php file to add the functionality.

add_filter ( 'wp_tag_cloud', 'tag_cloud_active_class' );
	
	function tag_cloud_active_class( $taglinks ) {
		if ( is_tag() ) {
			$term_id = get_query_var('tag_id');
			$taxonomy = 'post_tag';
			$args ='include=' . $term_id;
			$terms = get_terms( $taxonomy, $args );
			$active_tag = $terms[0]->slug;
		}
	    
	    
	    $tags = explode('', $taglinks);
	    $regex = "#(.*tag-link[-])(.*)(' title.*)#e";
	        
        foreach( $tags as $tag ) {
	        
	        if (strpos($tag,$active_tag)) { 
	        	$tagn[] = preg_replace($regex, "('$1$2 '.'active-tag'.'$3')", $tag ); 
	        } else {
	        	$tagn[] = preg_replace($regex, "('$1$2$3')", $tag );
	        }
        }
	        
	    $taglinks = implode('', $tagn);
	    
	    return $taglinks;
	}