WordPress: Tag Cloud Based on Author Posts

I’m currently working on a little russian social network powered by WordPress and I kinda got stuck this weekend on the user profile page. WordPress has got a pretty good mechanism for working with users, and the users meta piece is so awesome and useful. I’ve a little problem though, trying to output a tag cloud based on posts that a specific user has written.

In general this might seem simple, but for high performance the WordPress developers have mad a pretty complex taxonomy mechanism, that works like a charm, but I haven’t seen any author or author_id parameters in any of the taxonomy functions. Making a custom query to a database may be a little more complex than what I came up with, but I’m pretty sure it’s better at performance. Here’s the easy way:

$profile_user_id = get_profile("ID", "kovshenin"); // Replace this with yours
$profileTags = array();
$wp_query = new WP_Query("showposts=-1&author=".$profile_user_id);
while (have_posts())
	$tags = (array) get_the_tags();
	foreach ($tags as $key => $value)
		if ($value->term_id > 0)
			if (key_exists($value->term_id, $profileTags))
				$new_term = $value;
				$new_term->count = 1;
				$profileTags[$value->term_id] = $new_term;

$profileTagCloud = wp_generate_tag_cloud($profileTags);
echo $profileTagCloud;

What this does is it runs through all the posts by a specific user (kovshenin in my case) and retreives all the tags to each post via the get_the_tags function, then compares to what it has already collected in the $profileTags array and increments the count variable if that tag already existed there, or adds the new tag as an object into the array with count = 1.

You may find other parameters pretty useful too (link, slug, parent). I use the link parameter to lead to a new search by tag page limited to the specified user. Here’s a full list of parameters that should be included (and may be changed on the fly) and accepted by the wp_generate_tag_cloud function (using a print_r output):

    [0] => stdClass Object
            [term_id] => 6
            [name] => tag 2
            [slug] => tag-2
            [term_group] => 0
            [term_taxonomy_id] => 6
            [taxonomy] => post_tag
            [description] =>
            [parent] => 0
            [count] => 2
            [link] => "http://localhost/tag/tag-2"
            [id] => 6

Also, keep in mind that this is an object (of stdClass) and may not be treated like an array. I’m working on a custom SQL query directly into the WordPress database to achieve the same results but in less time (I hope). I’ll get back to you after the benchmarking.

2 thoughts on “WordPress: Tag Cloud Based on Author Posts

Comments are closed.