Posted In Internet

How To: Build a Tag Cloud with PHP, MySQL, and CSS

Tag clouds are everywhere. They are a popular way to show the weight (read: popularity) of tags, categories, or any words really. I needed to build a tag cloud for a project at work to display categories and show how many questions were contained inside each category. Categories with more questions would need a larger font, and categories with fewer questions would need smaller fonts. I came across this post from Steve Thomas titled How to make a tag cloud in PHP, MySQL and CSS.

Steve’s code is exactly what I was looking for. I made a few modifications to his code and wrapped it all into a custom PHP function, which you can see below.

Download The Code

The function returns an array that contains each category name, the CSS class that should be applied to the given category, and the category ID for linking to the page showing only questions in that category.

You’ll also need some CSS to style your tag cloud. This CSS is pretty much identical to what Steve published, I only made some minor changes to font sizes.

To use the function, do something like this:

I am still testing this code, but so far it seems to do exactly what I need it to do. It’s best to use tagclouds in a virtual private server provider that supports PHP, MySQL and CSS. If you experience trouble with the code or if it doesn’t act as expected, please let me know in the comments. If you’ve got ideas on how to improve the function, I’d love to hear your thoughts as well!

Well, now what?

Work with Me

I'm available for hire and always taking new clients, big and small. Got a project or an idea you'd like to discuss? Startup plan but no developer to make it happen? Just get in touch, I'd love to see if I can help you out!

Leave some Feedback

Got a question or some updated information releavant to this post? Please, leave a comment! The comments are a great way to get help, I read them all and reply to nearly every comment. Let's talk. :) is proudly hosted by DigitalOcean

About these ads
  • jim

    could you show the contents of category.php?

    • Jim, what are you taking about? category.php from TwentyTen or from Mystique? You can download either theme for free and look at category.php.

  • This seems like a great script.

    My skills in PHP (and virtually everything else except Flash) are less than minimal. I was wondering, could this script be adapted so that the tag cloud remains on my site and then can by changed/evolved by text inputs from visitors to my site?

    What I am really looking for is a kind of word cloud that each visitor to my site can contribute to so that it constantly evolves…

  • Plese note that you should no longer use the deprecated mysql_* used in my example in the post. Insteal use PDO or MtSQLi.