Advanced Filter for Tag Cloud Widget Css Classes

tag cloud widget colored with css
tag cloud widget advanced color styling

The default tag cloud widget does not offer a lot of formatting possibilities, partly because it only outputs one css class with a reference to the tag ID.
It uses an inline style, which outputs the font-size, to distinguish the tags according the number of post they belong to.

This filter function is coded to add a css class with the tag slug .tag-slug-{slug} and with a rounded tag size .tag-size-{number}, and to remove the inline style.

add_filter ( 'wp_tag_cloud', 'tag_cloud_widget_advanced_classes' );  

function tag_cloud_widget_advanced_classes( $taglinks ) { 
	$tags = explode('</a>', $taglinks);
	$regex1 = "#(.*tag-link[-])(.*)(' title.*)#e";         
	$regex2 = "#(.*style='font-size:)(.*)((pt|px|em|pc|%);'.*)#e"; 
	$regex3 = "#(style='font-size:)(.*)((pt|px|em|pc|%);')#e";         
	$regex4 = "#(.*class=')(.*)(' title.*)#e";         
	foreach( $tags as $tag ) {         
		$tag = preg_replace($regex1, "('$1$2 tag-slug-'.get_tag($2)->slug.'$3')", $tag ); //add .tag-slug-{slug} class   
		$size = preg_replace($regex2, "(''.round($2).'')", $tag ); //get the rounded font size       
		$tag = preg_replace($regex3, "('')", $tag ); //remove the inline font-size style
		$tag = preg_replace($regex4, "('$1tag-size-'.($size).' $2$3')", $tag ); //add .tag-size-{nr} class
		$tagn[] = $tag;
	}     
	$taglinks = implode('</a>', $tagn);     
return $taglinks; 
}

For the code, also see the pastebin.

The added css classes can for instance be used to color the tags according to the number of appearance; as you can see here in the tag cloud when you scroll down on the left.

2 Replies to “Advanced Filter for Tag Cloud Widget Css Classes”

  1. Hello!

    I pasted your code for the tags widget and it works! The only problem that I have is that I do not know where or how to place the font sizes .tag-size-{number}? If it is in the child css, can you please give me an example of what the code looks like? And if it is in the function.php could you give me an example aswell?

    Thanks!

    1. the styles belong into style.css (of your child theme);
      general examples:
      a.tag-size-8 { font-size: 8px; color: #CC3366; }
      a.tag-size-9 { font-size: 9px; }

      if your theme uses formatting on the links in the sidebar or widget areas (such as my theme in this site), you might need to use more specific styles;
      more specific examples:
      .widget-area a.tag-size-8:link { font-size: 8px; color: #CC3366; }
      .widget-area a.tag-size-9:link { font-size: 9px; color: #D8648B; }

Leave a Reply to alchymyth Cancel reply

Your email address will not be published. Required fields are marked *