HowTo use CSS to style the Wordpress Tag Cloud Widget
If you are using the Wordpress Tag Cloud widget (like you should be) and not hard-coding it in your template (like you had to back in the day) you will discover that you are unable to set any of the configuration parameters necessary to style it the way you like. If you call it directly from PHP in your template there are a few options you can use to control the look (kinda). Unfortunately the widgetized version does not give you access to those options so you’re stuck with the default — which is impossible to style with CSS. I’ll submit a patch to the Automattic guys to fix the Tag Cloud Widget but until it gets rolled into a release you can fix it with this little filter function without even touching the Wordpress core.
First lets take a look at the HTML the default Tag Cloud widget outputs:
<a href="http://www.c0defeed.com/?tag=wordpress" class='tag-link-1' title='3 topic' style='font-size: 8pt;'>wordpress</a>
Unfortunately the CLASS attribute is unique per tag and does not include any weighting information. And the STYLE tag hard-codes the font size based on weight but would override any CSS font-sizing we might have been able apply with the CLASS. Fortunately we can use the font-size information from the STYLE to determine the weight and write a small filter function to rewrite the CLASS and STYLE declarations so we can use CSS to style the tag cloud.
Here is the filter function we’ll be using to do the rewriting:
// Copy this code block to your functions.php file in your active template. // filter tag clould output so that it can be styled by CSS function style_tag_cloud($tags) { $tags = preg_replace_callback("|(class='tag-link-[0-9]+)('.*?)(style='font-size: )([0-9]+)(pt;')|", create_function( '$match', '$low=1; $high=5; $sz=($match[4]-8.0)/(22-8)*($high-$low)+$low; return "{$match[1]} tagsz-{$sz}{$match[2]}";' ), $tags); return $tags; } // Hook into the rendering of the tag cloud widget add_action('wp_tag_cloud', 'style_tag_cloud');
So what does that do? It rewrites the tag links to look like this:
<a href="http://www.c0defeed.com/?tag=wordpress" class='tag-link-1 tagsz-1' title='3 topic'>wordpress</a>
The default tag cloud uses font-sizes from 8 to 22 points. The filter function uses a regular expression to extract that size and remap the default range (8-22) to the range defined by the $low and $high variables, for this example I used 1 though 5. An additional CLASS is added ‘tagsz-n’ where ‘n’ is 1-5 and then the STYLE attribute is removed. With the additional class you can now add something like this to your style.css and make the Tag Cloud look any way you’d like!
a.tagsz-1 { font-size: 8px; } a.tagsz-2 { font-size: 10px; } a.tagsz-3 { font-size: 12px; } a.tagsz-4 { font-size: 14px; } a.tagsz-5 { font-size: 16px; }
If you find this useful I’d love to hear from you.
30 Sep 2008 Rick 2 comments
