DM Blog

WordPress Tag Cloud with Post Counts

by

I started my blog in as a way to improve my writing skills, as well as to get me using HTML on a regular basis. (Yes, all my articles are hand-coded in raw HTML.) But I didn’t expect that it would also lead to spending more time learning PHP and JavaScript. I used several different ready-made WordPress themes in my first year, but by the second year of having my blog I had created my own plugin and custom theme, which has evolved quite a bit over the years.

One of the things that has annoyed me about WordPress for a long time is the inability to display an article count next to each tag in a list (or within a tag cloud). On my archives page, I’ve always had the article count listed next to each month, category and author, but it’s been noticeably absent from the tags list.

So just this week when I was redesigning my blog yet again, (this time only two files changed – the CSS file and icon sprite), I decided to have another look at my theme’s archives page and see if there was anything I could do about it. I started by searching on Google and then by reading the documentation on WordPress.org for wp_tag_cloud();, and I still couldn’t find a WordPress-based solution to it, so I knew I’d have to tackle it with PHP alone.

If you look at the archives page on my blog, you’ll notice that I did indeed solve this finally, so Here’s the code to accomplish it (followed by a brief explanation):

<ul class="wp-tag-cloud">
<?php
	// get our tags as an array
	$tags = wp_tag_cloud('format=array');

	// loop through each tag in the array
	foreach ($tags as $tag)
	{
		// convert our string into an xml object
		$xml = simplexml_load_string($tag);

		// use our xml object’s attributes to output a new anchor tag
		echo '<li><a href="'.$xml->attributes()->href.'">'.$xml.'</a> ('.str_ireplace(' topics','',$xml->attributes()->title).')</li>';
	}
?>
</ul>

Short and simple.

When you use wp_tag_cloud('format=array');, it returns the tag cloud as an array, with each tag in the format: <a href="/tag/alberta/" class="tag-link-27" title="46 topics" style="font-size: 1em;">alberta</a>. So from there, I’m using PHP’s SimpleXML functions to re-format the tag cloud with the article counts appended.

Obviously, there are other ways to parse that string without using SimpleXML (using only string functions), but this was the quickest and simplest way that occurred to me. I like short and simple.