How to Make a Sexy Tag Cloud with PHP and MySQL
Posted by Nessa | Posted in ajax,mysql,ruby,scripts,wordpress | Posted on February 12, 2007
23
Well it seems that everyone has one, and I’d have to admit that a tag cloud is a good way to spice up your site a little bit. I first thought of this when setting up a friend’s site… he wasn’t using a CMS like WordPress or anything that I could find a quick tag cloud plugin for, so I figured I could probably just make my own. Well, I did and now I shall share it.
This tutorial will show you how to set up a simple tag cloud using PHP and MySQL, with a little bit of Ajax effects
Before we get started, take a quick look at the sample cloud.
Getting Started
The server requirements to make a tag cloud are minimal. You will need a new or existing MySQL database and PHP4+. It would also be extremely helpful to have something like phpMyAdmin or a MySQL command prompt to create the table.
Creating the Table
The first thing you need to do is create the database table. You can do this in either a new or existing database:
CREATE TABLE tags (
id int(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY(id),
tag varchar(100) NOT NULL,
count int(11) NOT NULL DEFAULT '0'
);
I ran this query via command line, but it may be easier to use phpMyAdmin or whatever database tool you use. Basically, this is a simply MySQL command that creates the ‘tags‘ table with three columns: id, tag, and count. The id table is being set to auto-increment, meaning that every time a new entry is added the number will go up by 1. Depending on how you are implementing your tag cloud, you may want to remove this value if you have trouble adding entries.
Creating the Cloud
Now for the actual code itself. In this section I will break down the script that fetches the tags from the database and creates a pretty tag cloud. At the end you will find a full sample script that you can use for reference.
$db_host = "localhost";
$db_user = "username";
$db_pass = "password";
$db_name = "cloud";
mysql_connect($db_host, $db_user, $db_pass) or die(mysql_error());
mysql_select_db($db_name);
This is the section where you define a few variables and use them to connect to the database. You wil obviously need to input your database name, username, and password in order to allow the script to connect.
function tag_info() {
$result = mysql_query("SELECT * FROM tags GROUP BY tag ORDER BY count DESC");
while($row = mysql_fetch_array($result)) {
$arr[$row['tag']] = $row['count'];
}
ksort($arr);
return $arr;
}
This is the function that grabs the tag information from the database and displays everything in the tag column as an array. Now to build the cloud:
function tag_cloud() {
$min_size = 10;
$max_size = 30;
$tags = tag_info();
$minimum_count = min(array_values($tags));
$maximum_count = max(array_values($tags));
$spread = $maximum_count - $minimum_count;
if($spread == 0) {
$spread = 1;
}
$cloud_html = '';
$cloud_tags = array();
foreach ($tags as $tag => $count) {
$size = $min_size + ($count - $minimum_count)
* ($max_size - $min_size) / $spread;
$cloud_tags[] = '<a style="font-size: '. floor($size) . 'px'
. '" class="tag_cloud" href="http://www.v-nessa.net/index.php?s=' . $tag
. '" title="\'' . $tag . '\' returned a count of ' . $count . '">'
. htmlspecialchars(stripslashes($tag)) . '</a>';
}
$cloud_html = join("\n", $cloud_tags) . "\n";
return $cloud_html;
}
?>
Take special note of this code:
class="tag_cloud" href="http://www.v-nessa.net/index.php?s=' . $tag
In this section I’m basically telling the script to append the tag name at the end of a link…in this case it’s my search path, meaning that clicking on, for instance, the ruby tag will take you to this link:
http://www.v-nessa.net/index.php?s=ruby
This will just take you to a search for the term “ruby” on my site, but you can specify how you want the tag name to be incorporated into a link. For instance:
class="tag_cloud" href="http://www.v-nessa.net/tags/' . $tag
The above example shows the primary purpose of a tag cloud, which will take the tag pulled from a database and pull all articles under that tag. An example of this is on the menu of my site, to the right.
The last part of the script should be the style sheet, which will direct how the cloud will look:
<style type="text/css">
.tag_cloud
{padding: 3px; text-decoration: none;
font-family: verdana; }
.tag_cloud:link { color: #FF66CC; }
.tag_cloud:visited { color: #9900FF; }
.tag_cloud:hover { color: #FF66CC; background: #000000; }
.tag_cloud:active { color: #6699FF; background: #000000; }
</style>
To Display the tag cloud, you just need to insert this code into your web page (or sidebar):
<div id="wrapper">
<?php print tag_cloud(); ?>
</div>
And there you go…your very own tag cloud. You’ll of course need to populate the table with your own tags, ids and count numbers, or plug this script into your blog to fetch the tags from its database.
You can find a full copy of the script here.
No related posts.














This is a cool script!
I have visited your site 030-times
This is really cool script. But your full copy of script is unavailable on the link :
http://www.v-nessa.net/scripts/tag_cloud.phps
Anyway, I can that that zip file. I am able to populate database, allocate weights to tags but quite new in php to figure out which file goes where :)
Thanks
yea, sorry about that. here it is:
http://www.v-nessa.net/scripts/tag_cloud.phps
Nice, brief and clear. I like it.
Thanks
[...] envy those sexy tag clouds you see on other blogs? You can always make your own, but for WordPress, Ultimate Tag Warrior is the best way to create your own customizable tag cloud. [...]
i have error in this script i want help for add yhis script in my script onarcade games can you help
nice but ı dont understand..
http://www.v-nessa.net/tags/‘ . $tag <<in this type how give $tag in browser ?
how listing topic that contain tags
THANKS. this is brilliant. i’ve been trying to figure out php/mysql and fiddled around with this forever until i got it to work (working on a thing of my own)
yeayeayeayeay
beautiful. i´ve adapted this to my own copy of the great mantis (1.1.6 works like a charm by the way). not possible without you. i needed to link using the “tag_id” but as i did not have that in the single array i made it 2-dimensional. the solution i created is not to ellegant but works. THANKS!
My db has multiple tags seperated by a comma, ie “candy, ice creame, cake” etc.
I’m having a challenge making a normalized table in step 1
Love the site.
thanks
I need the SQL result to pull from a keywords table instead. the structure is pp_photos.keywords
How would I rewrite the mysql $result to work.
I tried some variations, but cannot get it to pull?
I am talking about this line: $result = mysql_query(“SELECT * FROM tags GROUP BY tag ORDER BY count DESC”);
What will the script do if there is no incrementer for the ID in place? Will it just list the tags, rather than placing weight on them? How about Count = What exacly is that supposed to do?
@Martin if there’s no incrementor, the id will be duplicated which will likely not work
Hi,
Can you help me …
I wish to limit number of tags for displey …How can I do theat …
Thank you for help …
@Neso
Use limit:
$result = mysql_query(“SELECT * FROM tags GROUP BY tag ORDER BY count DESC LIMIT 50″);
That will limit to 50 tags
Hi,
I need the link goes to the “link” column of my database
Already try this but doesn’t work
. ‘” class=”tag_cloud” href=”http://www.???.com/test/index.php?q=’ . $link
Hi,
Hi have a problem. When I try to make a search with this word “world’s” give me this error. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘s’ LIMIT 1′ at line 1. I think is a problem with sigle quotes. Do you have any fix?
Thank you,
Best regards,
Rato
Hi Nessa,
If you don’t mind, a high school biology teacher (me) needs your help for this tag cloud script. The linking part is working just fine. The problem I am having is that the script is not counting the number of tags I have for each row entry. It is saying : returned count of 0. The other problem is the comma separated tags name, name2, etc. for each bookmark’s entry tags are tag clouded as a group instead of separate words.
I have been searching on the Web for three days and cannot find a solution for these questions.
Is this script suppose to count the tags and put that information back into the dbase and then output it to the tag cloud? or Is this suppose be happening another way, say like when a person post a new entry with added tags?
How are you implementing script wise for the tag cloud in the right margin on this page? I can see that you are getting the count numbers.
Sincerely,
Charles
thanks so much..
i’m really helped by u..
How can I make it read arabic words? when i put arabic words it gives an output of (??????) question marks!
any clue?
It’s not the tag cloud, it’s probably a bad PHP setting. Try commenting out the charset line in php.ini
Surprisingly easy to implement, I’ve been searching for a decent one with database integration and here we are, thanks and keep it up!