jump to navigation


Building A Tag Cloud in WordPress March 15, 2006

Listen to this article (Listen to article)

Some weblogs display a feature known as a tag cloud. This consists of the blog’s categories shown in varying font sizes. (See the bottom of the navigation sidebar.) The larger the font used for a specific category, the more posts that category has. Each category in the tag cloud links to a page containing all of the posts falling into the category. [MINOR REVISION: Mar 28/06]

The idea behind the tag cloud is that it gives visitors a visual cue as to the focus of the weblog. It’s much easier to tell, compared to a list of categories and their post counts in brackets. Depending on the type of blog platform you are using, it’s relatively easy to set up your own tag cloud. Some platforms such as Blogger.com do not support categories and hence cannot have a native tag cloud. However, you could rig one using externally classified and stored categories. (Sorry, that isn’t the focus of this post.)

The example tag cloud code that I came across at Technology Evangelist was for the Movable Type blog platform. I’m presenting a similar solution for WordPress. I’m using the CSS (Cascading Style Sheet) code from the Technology Evangelist example. Copy and paste their CSS code into your WordPress theme’s main stylesheet. Depending on your theme, this file is probably called style.css. Insert the TechEv CSS code at the bottom of your main stylesheet.

While there are built-in WordPress functions (PHP code) to retrieve your blog’s post categories, most of them pre-format the category names and links. To create a proper tag cloud, we want to retrieve each category name alphabetically. Then we want to assign each a font size proportional to its post count.

For example, if category traffic has 3 posts and category plugins has 10, the latter category name should be shown in a much larger font size than the first. If there’s another category which has a number of posts that falls between these two, then its displayed font size will be in between as well.

As mentioned above there are built-in WordPress functions for auto-formatting and displaying category lists and links. These are commonly used in WordPress themes to create the components of the navigation bar. Unfortunately, you cannot wrap additional HTML tags and attributes around each category name with these functions. Since we need to add a class attribute around each category so that we can control font size, that means we have to access the category information directly from the appropriate database tables, then massage the info.

To get an understanding of the code to follow, let’s first look at the WordPress database tables that we need to access for the tag cloud:

  1. wp_categories. This table contains information about the different categories you have created for your blog posts.
  2. wp_post2cat. This table matches each post in your blog to one or more cateories, depending on how you categorized the post. We need to access this table because WordPress does not store the current number of posts for each category in the wp_categories table.

The general algorithm is as follows:

/* Initialize category post counters */
Retrieve all the rows in table wp_categories
For each row retrieved
{
  Initialize the current category's post counter to zero
}
	
/* Determine category counts */
Retrieve all the rows in table wp_post2cat
For each row retrieved
{
  increment the post count for the specified category
}
	
/* Build tag cloud */
For each category
{
  Get the link for this category using the WP function get_category_link()
  Output the category name and its corresponding link,
      but assign the <a href=""> tag an attribute of class="tagN",
      where N is the post count.
}

Fortunately, WordPress has a wpdb (WordPress Database) PHP class with which we can access database tables and their contents relatively easily.

Using the above algorithm, we can write PHP code for building a tag cloud. Each category is wrapped in a hyperlink reference that uses a class attribute. The actual attribute consists of the string “tag”, followed by a number representing the post count for the given category.

The CSS code will ensure that each category name is displayed in an appropriate font size. The CSS code from Technology Evangelist only goes up to a count of 30 (tag30) , although you can modify it as necessary. Counts that are close together often use the same font size. Feel free to adjust the CSS code to customize it.

Here is the PHP code that I came up with. Be careful with the single and double quotes. Unless you know what you are doing, I’d suggest you stick with what I’ve got.


<!-- Tag Cloud code: start -->
<?php
// Grab category info from the database table wp_categories
$qrystr = "SELECT cat_ID, cat_name from $wpdb->categories";
$cats = $wpdb->get_results($qrystr); // Default output type: object
	
// Initialize each category post counter to zero
// Save category info as an array of objects
foreach ($cats as $cat)
{
  $catcnt[$catid]->cat_ID = $cat->cat_ID;
  $catcnt[$catid]->cat_name = $cat->cat_name;
  $catcnt[$catid]->postcnt = 0;
}
	
// Grab the post-to-category info from table wp_post2cat
$qrystr2 = "SELECT post_id, category_id from $wpdb->post2cat";
$post2cats = $wpdb->get_results($qrystr2);
	
// Now count the number of posts for each category
foreach ($post2cats as $post2cat)
{
  // You could do the following in one line, but I've
  // done it in two for clarity.
  //
  $pcatid = $post2cat->category_id;
  $catcnt[$pcatid]->postcnt += 1;
}
	
// Now output the tag cloud
	
echo '<br/><div id="cloud">';
foreach ($catcnt as $catinfo)
{
  $catname = $catinfo->cat_name;
  $catlink = get_category_link($catinfo->cat_ID);
  $postcnt = $catinfo->postcnt;
  echo '<a href="',$catlink,'"';
  echo ' class="tag',$postcnt,'">';
  echo $catname,"</a> ";
}
echo "<br/></div>";
?>
<!-- Tag Cloud code: end -->

This code isn’t perfect. For example, the resulting tag cloud - at least in my WordPress theme - shows each category on a separate line despite any obvious break. This isn’t the proper way to do a tag cloud, but it’s a start. (You can see the results at the bottom of this page’s navigation sidebar.) What’s more, the categories are not sorted by name. I’ll fix these problems when I have a bit more time, and post details here.

Note that the PHP code has to be inserted into your WordPress theme’s sidebar template. Where you insert it of course depends on where you want it to appear. I’ll leave that to you. At some point in the near future, I’ll turn this code into a WP plugin, which I’ll announce here on this weblog. However, if you beat me to it, please let me know. Use the code however you like, but don’t blame me for any problems :)

Technorati Tags: , , , , ,



Comments»

1. Gregg F - March 28, 2006

Thanks for your hard work on this modification. I’ve imported it into my theme on http://blog.nextblast.com and it works nicely. The only thing I changed was to add a small spacer between the individual categories within the cloud by changing the css #cloud a {text-decoration:none;padding:0px;} to #cloud a {text-decoration:none;padding:4px;}. Next thing I’d like to do, or someone else to beat me, is to do an alphabetical sort of the category names.
Thanks again.

2. rdash - March 28, 2006

Greg, that’s great. I’ll admit, my code is messy. Because of other pressing matters, I didn’t explore the CSS too much. The alphabetical list is actually really easy. The honest truth is, for the life of me, I couldn’t remember how to sort a hash table in PHP. It’s so simple, but my memory fails me. Once I remember, I’ll update the code here and change the date of this post. (With a “revision” note in the first paragraph.)

3. Whitewater Mobile Journal » Item Category Cloud Navigation - April 3, 2006

[…] I just implemented a catagory tag cloud on this site as created by rdash as documented within his description called Building a Tag Cloud in Wordpress at the CodeProfessor journal and the cloud CSS as documented at the Technology Evangelist. Even though the published article at the Technology Evangelist is for Movable Type it works quite well in the wordpress theme. I just made a minor modification to add more space between the item category tags. Next, I’ll improve by alphabetizing the order of the tags. […]

4. CodeProfessor » 5 Types of Tag Clouds - May 2, 2006

[…] Markus wrote a post over at Performancing about tag clouds and started an interesting discussion. Yours truly added a few comments. At first glance, it may seem that a tag cloud is a tag cloud is a tag cloud, but there are several distinct differences, as far as the source information used to build the clouds in concerned.  I’m summarizing here my conclusion about tag clouds, based on the discussion that Markus started. […]

5. Stupid Wordpress Tricks » Building a Tag Cloud in Wordpress - May 4, 2006

[…] This is a neat article on how to build a tag cloud in Wordpress, from codeprofessor.com. […]

6. CodeProfessor » Tag Graphs - An Alternative To Tag Clouds - May 26, 2006

[…] 45 Royale, a web design firm,  has a feature in their “notebook” that makes me ask why didn’t I think of that? Instead of a tag cloud, they use something called a tag graph. A little bit of thought, and I realized they’re not hard to create in PHP and a bit of CSS. [This post is a general discussion. I’ll come up with exact code for WordPress in another post.] […]

7. annka - July 11, 2006

Hi!
I just found your site, when I was looking for code for a tag-cloud. Your code helped me much, but ofter understanding this tag-cloud thing and teh possibility to use the data from the database of wordpress, I found an easier way to implement it and also sort it. In the table you use (wp_categories) is also a column which is called categorie_count. There is saved how many post in every category are, so you don’t need to count it again. I don’t know, if you had other reasons to do so, but if you don’t need to count the code is pretty short and in this case you can the odering just do in the mySQL query. For your interest: this is my code:

categories ORDER BY cat_name”;
$cats = $wpdb->get_results($qrystr); // Default output type: object

//read and write the category data
echo ‘’;
foreach ($cats as $cat)
{
$catname = $cat->cat_name;
$catlink = get_category_link($cat->cat_ID);
$postcnt = $cat->category_count;

echo ‘ ‘;
echo $catname.”
“;
}
echo “”;

?>

Thank you! Without your basics I wouldn’t have been able to get my tag-cloud work.

8. annka - July 11, 2006

Ok, I should have masked the code somehow… If you want to have the code completely, just write me an eMail.

9. rdash - July 21, 2006

Annka: Thanks very much for the code. I’m sorry for not responding, as I didn’t see your comment until just now. Very simple and succinct code!

10. Google Success - July 27, 2006

Thanks for sharing your code. I tried it in my wordpress based blog and works just as I wanted it !!

11. Links Sizzler - July 27, 2006

It’s a marvelous piece of code for generating word cloud blogs. I found a similar sorce code for genrating word tags at

http://www.15tags.com/blog/tagcloud-demo-with-source

Enjoy it !

12. rdash - July 28, 2006

Thanks for the heads up, links sizzler

13. PHP: Tagcloud? » Betamode - September 6, 2006

[…] http://www.technologyevangelist.com/2006/03/how_to_make_a_tag_cl.html http://www.codeprofessor.com/journal/2006/03/15/building-a-tag-cloud-in-wordpress/ http://w.astronote.jp/index.php?TagCloud.php http://www.hawkee.com/snippet.php?snippet_id=1485 Thema: Kram Keine Kommentare - :( […]

14. Perfect Blogger - September 21, 2006

How To Improve Your Blog Usability And Why You Want To Do It

Usability of your blog is one of the most important factors of how successful and popular it is. Yet, it is often neglected.

15. Chris - October 3, 2006

One of the first things I did when I started playing with WordPress was build a simple plugin to give me a word cloud based on my blog post content.

The tag cloud of categories idea is interesting too! It sure does simplify the keywords that may end up in the cloud, especially if you are working with the search engines.

16. links for 2006-10-19 at willkoca - October 31, 2006

[…] CodeProfessor » Building A Tag Cloud in WordPress (tags: tagcloud php wordpress) […]

17. Aaron - December 21, 2006

Great post! Just what I was looking for. ;)

18. pseudotecnico:blog » Blog Archive » Wordpress: tag cloud per le categorie - December 25, 2006

[…] In questa piccola guida vedremo come costruire una tag cloud artigianale per le categorie prendendo spunto dallo script presente in questa pagina. Questo è il codice da inserire nella sidebar (è disponibile un file di testo con il codice): […]

19. PseudoTecnico - December 26, 2006

If someone is interested, I realized a slightly different version of this code.
You can find it in the address of the previous trackback: even if comments and variables’ names are in italian, I think that the code should be clear):
* as suggested by annka, it uses only one array
* it doesn’t use a class for each tag, instead it calculates a percentage value for font-size property based on three variables: max_percentage ($percentuale_massima), min_percentage ($percentuale_minima), percentage difference between tro levels ($percentuale_scalino).
* assign a title attribute to tag a with the number of posts (you will see a tooltip)
* it gives a class only to the top post category (or categories), just in case you want to style it

20. Sean Sullivan - January 12, 2007

Interesting post! I’ve been doing a lot of work with tag clouds as of late and I used one of my methods to piece together a WordPress plugin to quickly get one fired up. The Plugin is actually a Widget for the WordPress Widgets Plugin that helps you easily customize your sidebar. Check out my post on my blog to learn more and download if you’d like to try it out. The plugin uses your category tags and represents their popularity as a measure of font-size. Similar to the method you’re discussing.

http://www.ryboe.com/2007/01/11/ryboe-tag-cloud-plugin-for-wordpress.html

21. metal.ize » Blog Archive » Paginas 404 útiles - March 20, 2007

[…] Una nube de tags y entradas relacionadas son un buen elemento para empezar nuestra página de error. Así le estamos dando opciones al usuario y buscando una posible solución a su problema. Para esto necesitaremos algunos plugins que puedan crear nuestra nube de tags. Existen muchas alternativas, pero la que yo uso se llama Jermoe’s Keywords. Bastante estable y adaptable, para ser un beta. Sin embargo, debo recomendar que instalen el related entries; pues para el objetivo de nuestra página de error amigable les ahorrará dolores de cabeza, ya que tiene una extensión para agregar entradas relacionadas a tus páginas de error 404. […]

22. torama blog » 2007 » April » 10 - April 10, 2007

[…] Vous avez peut-être remarqué que le menu des catégories est passé en ‘tag cloud’, système rendu célèbre par Flickr. J’utilise une version simplifiée du code trouvé sur CodeProfessor. Retenez juste qu’il y a bien une colonne category_count dans la table, contenant le nombre d’articles de la catégorie. […]

23. links for 2007-04-11 « Coruxa Xusticiera - April 11, 2007

[…] CodeProfessor » Building A Tag Cloud in WordPress (tags: tagcloud wordpress php) […]

24. Collection of Tools/Sites to Create Tag Cloud - Home for all things technical - April 22, 2007

[…] CodeProfessor: Building A Tag Cloud in WordPress […]

25. The K-log - May 17, 2007

[…] i decided to search around again for options and advice, and i found very fruitful beginnings in: this blog entry wherein the code professor churns out some wordpress-ready php for cloud-building, he being inspired in turn by the technology evangelist writing about using php and css to build tag clouds for movable type blogs. […]

26. CakeFlash » Fleshing out CakeFlash #2 - August 4, 2007

[…] http://www.codeprofessor.com/journal/2006/03/15/building-a-tag-cloud-in-wordpress/ […]

27. Śmieszne filmy - September 9, 2007

Great post! Just what I was looking for. ;)

28. Jose Ochoa - September 14, 2007

Hello, this look fine, but how i can use this to Wordpress MU? any ideas?, maybe creating an resume table? thanks.

29. electric elephant » Blog Archive » links for 2007-11-29 - November 29, 2007

[…] CodeProfessor » Building A Tag Cloud in WordPress (tags: wordpress tagcloud blogs design plugins howto tools typography webdesign) […]

30. Interesting websites for SEO, Web Marketing and everday work from Sante - January 26th - January 26, 2008

[…] Building A Tag Cloud in WordPress - the tag cloud is that it gives visitors a visual cue as to the focus of the weblog […]