Creating an accessible tag cloud in PHP and CSS (with MySQL)
Tag clouds; love them or hate them they're an unavoidable cliche that clients seem to love. Once marketing types get the smell of taxonomy in their nostrils it's hard to convince them that tag clouds are a usability nightmare.
Therefore to go along with the trend (well, a trend from 12 months ago maybe) I decided to implement a tag-cloud with this website, the intention was to demonstrate how it can be done in a clean and tidy fashion using simple code. The one noted in this tutorial is accessible and standards compliant, something which seems hard to come by elsewhere...
Why other tag clouds are rubbish
Without wanting to be too cruel to some other developers, almost every tag cloud tutorial on the Internet is awful. The PHP is either far too complicated for the purpose or it relies on inline styles (or both). The PHP doesn't need to be lengthy, after all it's a very simple calculation and the CSS needs to reflect that. Do we really need 100 different sizes that the tag-cloud could be? Unlikely.
How mine works
Here is the basic set of steps to create an accessible, valid tag cloud:
- Count how many pieces of content there are in total [x]
- Count how many pieces of content are assigned to each tag [y]
- Work out what percentage of [x] that [y] constitutes
- Apply a CSS class that reflects that percentage
Therefore if you have 100 articles [x] and 19 articles [y] tagged with "kitten", then "kitten" constitutes for 19% of your content. I'll show you how to apply this logic in PHP and write out valid XHTML in the process.
The code
Let's start with the PHP, I'll comment the code for ease of understanding:
The above function takes an array of tags, iterates through them and gets each tag as a percentage of the total number of pieces of content. I'm rounding to the nearest 10 because I think 10 different font-sizes in a tag-cloud is more than enough. Now the CSS:
That will create a nice unordered list of tags, lined up next to one another and nicely weighted with 10 different font sizes depending on their proportional popularity within your entire content archive.
How to make tag-clouds usable
In the majority of cases tag-clouds are only made into a usability nightmare by the user. Clouds are inherantly a good idea but stereotyped by poor implementation. For a tag cloud to be usable it should:
- Be clear and concise
- Have as few tags as possible, 10 is probably best, but certainly less than 30
- Use sensible, descriptive tags. Using "stuff" as a tag isn't going to be helpful to anyone
- Ensure that even the least popular tags are still of a readable size
- Be standards compliant (no inline styles)
For an example of an automatically generated tag-cloud that was less than useful, see my article on Seopher.com about the world's biggest tagcloud; one created on the previous implementation of the 9Rules blogging network. Remember, less is better.
Tagged with xhtml, css, php, accessibility
