A better WordPress tag cloud

Posted September 4, 2009 by Brian Cray

Reading time: About 1 minute

A bit of copy & paste code that will make your WordPress tag clouds better looking and better performing.

Why WordPress’ tag cloud is crap

  • Isn’t valid HTML
  • Uses PHP‘s create_function(), which is no better than eval() (dangerous and slow)
  • The code itself is messy gobbledygook

Introducing a better WordPress tag cloud

  1. Copy this code into /wp-content/themes/yourtheme/functions.php
  2. Run <?php echo get_my_tags(); ?> wherever you want a tag cloud
  3. Make sure the tag archive URL on line 40 points to the right place
  4. Optionally change $smallest and $largest (on lines 3 & 4) to the preferred pixel size of your smallest and largest tags

You can see a working example of this code on my main blog index page.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
function get_my_tags()
{
	$smallest = 14;
	$largest = 26;
	$tags = get_tags();
	$counts = array();
 
	foreach($tags as $key => $tag)
	{
		if($tag->count < 2)
		{
			unset($tags[$key]);
		}
	}
 
	foreach ( (array) $tags as $key => $tag )
	{
		$counts[ $key ] = $tag->count;
	}
 
	$min_count = min($counts);
	$spread = max($counts) - $min_count;
 
	if ( $spread <= 0 )
	{
		$spread = 1;
	}
 
	$font_spread = $largest - $smallest;
	if ( $font_spread < 0 )
	{
		$font_spread = 1;
	}
 
	$font_step = $font_spread / $spread;
 
	$html = '<p>';
	foreach($tags as $tag)
	{
		$html .= '<a href="/tags/' . $tag->slug . '/" style="font-size:' . round($smallest + ($tag->count - $min_count) * $font_step) . 'px">' . $tag->name . '</a> ';
	}
	$html .= '</p>';
	return $html;
}

About the author

Photo of Brian Cray

Brian Cray is a Columbus, Ohio-based web entrepreneur & consultant. View some of Brian’s work in his portfolio and learn how to make kick ass websites by reading his blog.

23 Article comments

Show/add comments

4 Article references from other blogs

Show all references

1222
Previous:
Next: