WordPress Tag List With Counts
August 27th, 2011 (5 months ago)
Introduction
If you’re wondering how to make a WordPress tag list with their respective counts when you’re outside of the loop, then you’ve come to the right place. I came upon this issue when I was building the sidebar navigation for this site. Generally speaking, I couldn’t find much information on the subject so I had to resort to my own solution. After scouring the WordPress codex for relevant and usable functions I was able to figure out a method that worked for me.
The Plan
- Get all the tags WordPress has stored.
- Associate the tags with their respective counts.
- Sort the tags by alphabetical order.
- Print out the list.
Get all the tags WordPress has stored.
I couldn’t find any WordPress functions that returned all of the tags that WordPress stored so I had to find some way of extracting that information directly from the WordPress database. After a little snooping around my local PHPMyAdmin panel, along with some light reading on the subject of WordPress terms and taxonomy, I found out where all the tags were being stored. If you take a look inside the wp_term_taxonomy table you’ll find a field called “taxonomy” where WordPress stores the names of the types of terms being stored. Of all the names stored, “post_tag” is obviously the one we want.
The wonderful thing about WordPress is that it makes querying the database much easier with its $wpdb class which is stored in a global variable. If you aren’t familiar with this class you should really check out the documentation when you get the chance. You’ll definitely find it a necessity if you should ever get around to programming your own plugins. For our purposes, we’ll be requiring the class to help us extract information from the database. Here is the our database query using the $wpdb class.
// Get the tags
global $wpdb;
$query = “SELECT * FROM wp_term_taxonomy WHERE taxonomy=’post_tag’;”;
$rows = $wpdb->get_results($query);
The first thing to remember to do is the globalize the $wpdb variable so that we can properly utilize it. Just to make things spaced out and clear we store our query string into the $query variable. Then we use the get_results() function found within the $wpdb class to perform our query. As you can see, the results are stored as an object into the $rows variable. Again, if you’re curious to see what values are stored in that object check out the documentation.
Associate the tags with their respective counts.
Now that we have a collection of post_tag information, we can now go through each one and extract a term_id which we’ll need in order to get the string value of the tag, the number of posts associated with the tag, and the tag’s permalink. With the help of WordPress’s get_term() and get_tag_link() functions we’ll be able to this. But before we get into a loop to iterate through our $rows object, we first have to create an array where we’ll store this information into a variable, which we’ll call $tag_list.
// Associate tags with counts
$tag_list = array();
if($wpdb->num_rows>0){
foreach($rows as $row){
$term = get_term((int)$row->term_id,‘post_tag’);
array_push($tag_list,array(
‘name’ => $term->name,
‘count’ => $row->count,
‘link’ => get_tag_link((int)$row->term_id)
));
}
}
The get_term() function takes two arguments: the term_id and taxonomy name. The object that gets returned has a property called “name” which we use to get the string representation of the tag. The number of posts associated with the tag can be found in the “count” property of each $row object. Finally, to get the tag’s permalink we use the get_tag_link() function, which takes in a term id value. We store all this information into an associative array which, in turn, gets added to the $tag_list array.
Sort the tags by alphabetical order.
Now that we’ve neatly collected the required information about our tags, we need to sort the $tag_list array in alphabetical order. To do so we first need to set up a comparative function that will sort our multi-dimensional array according to its children’s “name” element. (Remember that we stored a “name”, “count”, and “link” element into each child array.) Below is the comparative function we’ll be using, which should be placed into the functions.php file.
// Comparative function – alphabetical
function compare_alphabetical($a,$b){
if($a["name"]==$b["name"]){
return 0;
} else if($a["name"]>$b["name"]){
return 1;
} else {
return -1;
}
}
I’m still not knowledgeable enough to know exactly how sorting functions work but by just looking at the code you can get a gist of what’s going on. Notice that two arguments are being passed into the function, which represent two elements from the array we’re sorting. Instead of comparing the value of the elements, which are arrays, we compare the value of their “name” element. Depending on the conditions we return a -1, 0, or 1, which is a requirement of all sorting functions. Note that by switching $a and $b around, we can reverse the result of the final sort.
Moving on, we can now properly sort our $tag_list array with the following code:
// Sort by alphabetical order
usort($tag_list,“compare_alphabetical”);
Print out the list.
Once we’ve sorted our list of tags, we can finally write out our list in HTML. The following is the complete version of our code.
<ul>
<?php
// Get the tags
global $wpdb;
$query = "SELECT * FROM wp_term_taxonomy WHERE taxonomy='post_tag';";
$rows = $wpdb->get_results($query);
// Associate tags with counts
$tag_list = array();
if($wpdb->num_rows>0){
foreach($rows as $row){
$term = get_term((int)$row->term_id,'post_tag');
array_push($tag_list,array(
'name' => $term->name,
'count' => $row->count,
'link' => get_tag_link((int)$row->term_id)
));
}
// Sort by alphabetical order
usort($tag_list,"compare_alphabetical");
// Write the list
foreach($tag_list as $tag){?>
<li>
<a href="<?php echo($tag['link']); ?>">;
<?php echo($tag['name']); ?> (<?php echo($tag['count']); ?>)
</a>
</li>
<?php }
}
?>
</ul>
We begin in HTML by opening an unordered list element. Immediately after, we place the code we’ve been working on from the beginning. You’ll notice the final piece of code we added is a loop that iterates through our neatly sorted $tag_list array. Within each loop we add a list item element which holds an anchor link. By accessing the $tag array we can furnish our HTML appropriately as needed. We end by exiting PHP and closing up our unordered list.
Closing
There you have it! A WordPress tag list, with their post counts, created outside of the loop. I suppose you could use the same principles to get a list of categories as well if you wanted to do something fancy with that information. In any case, I hope that you found this tutorial helpful and informative. As always, your questions or comments are always welcome below. Until next post, happy tag-listing!
TAGS: ALL, Tutorial, WordPress
0 comments