Here is another post containing a snippet of code that you can use in your own project or just so that you can store it in your "Useless Snippets Folder" on your Desktop. You can view all of the older code snippet articles by browsing the code snippet category list.
This code can be used to make a simple and easy tag cloud for your categories or tags on your own website or blog. It uses a simple mathematical sum to calculate a percentage for the font size of each tag and then returns it in a XHTML-compliant, inline list. The function requires an array of the tags in the format: "$tags['tag_name'] = tag_count;", when tag_name is the name of the tag and tag_count is the amount of instances the tag has.
Anyway, here is the code:
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 | <?php function tag_cloud($tags) { if (!$tags) { return false; // Error: no $tag argument was specified. } $max_size = 250; $min_size = 100; $largest = max(array_values($tags)); $smallest = min(array_values($tags)); $range = $largest - $smallest; if ($range == 0) { $range = 1; } $step = ($max_size - $min_size) / ($range); $content = '<ul style="list-style: none; padding: 0; margin: 0;">'; foreach ($tags as $key => $value) { $size = $min_size + (($value - $smallest) * $step); $content .= '<li style="display: inline; padding: 5px;"><a href="#" style="font-size: ' . $size . '%" title="'. $key . ' (' . $value . ')">' . $key . '</a></li>'; } $content .= '</ul>'; return $content; // Return: return the output content, conating the formatted tags. } ?> |
For example, you could use the function as follows:
1 2 3 4 5 6 7 8 9 10 11 12 | <?php $tags['tag1'] = 21; $tags['tag2'] = 54; $tags['tag3'] = 42; $tags['tag4'] = 12; $tags['tag5'] = 32; $tags['tag6'] = 12; $tags['tag7'] = 54; $tags['tag8'] = 35; echo tag_cloud($tags); ?> |
Which would output the following:




Bull3t's Blog is a next generation web log written by me, Philip Hughes (also known as Bull3t), a first-year college student living in England, aged 17. I write this blog for the sake of doing so, posting about anything I see fit. 

So what now?
You've reached the end of this post. Seeing as you made it this far means you might be interested in the following related articles and resources.2 Comments
September 29th, 2007
#1
I am not much of a fan of the tag cloud for blogs, however that is a great tutorial for learning PHP. I think tag clouds make your blog look like every other blog in the world. I would just rather put the number of posts next to each category/tag, which looks much nicer.
September 29th, 2007
#2
True, nearly every single blog has tags and tag clouds, I was not a fan of tags until WordPress 2.3 had them built in so I thought I may as well make use of them.
Leave a reply