Written by Brian Cray on September 4th, 2009
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
- Copy this code into /wp-content/themes/yourtheme/functions.php
- Run
<?php echo get_my_tags(); ?>wherever you want a tag cloud - Make sure the tag archive URL on line 40 points to the right place
- Optionally change
$smallestand$largest(on lines 3 & 4) to the preferred pixel size of your smallest and largest tags
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;
}