Brian Cray ··· Home > Blog > Php, Wordpress > A better Wordpress tag cloud

A better Wordpress tag cloud

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

Why Wordpress' tag cloud is crap

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
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;
}