How to Make a Sexy Tag Cloud with PHP and MySQL

Tag CloudWell 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.


Be Sociable, Share!

Leave a Reply

Your email address will not be published. Required fields are marked *