Create a list of categories and tags in WordPress

This is more for personal use I suppose. Once upon a time, I needed to create a unified list of categories and tags for a post. I went about it the wrong way, getting all of the terms  for both, merging them using array_merge() and then looping through the list to get generate an unordered list. There is a simpler way…

[php title=”Create combined list of tags and categories”]
<?php
$terms = get_the_terms( $sched_post->ID, array( ‘category’, ‘post_tag’ ) );
if (!empty($terms)) {
$output .= ‘<li>Topics: ‘;
$the_terms = ”;
foreach ($terms as $idx => $term) {
$the_terms .= ‘, <a href="’ . get_term_link( $term ) . ‘">’ . $term->name . ‘</a>’;
}
$output .= substr( $the_terms, 2 );
$output .= ‘</li>’;
}
[/php]

The documentation for get_the_terms() used to say that you could only pass in a string of the taxonomy name. It is possible to pass in an array, and get an ordered list of terms back from all taxonomies. I’ve updated the documentation in the WordPress.org Codex to reflect this. Kinda neat. You don’t always need to have categories and tags together, but this saves merging/sorting and so forth.

You can see this in action on Maker Faire profile pages, like Todd Blatt.

Another related trick that I found the other day was using strip_tags() along with get_the_term_list(). I needed to output the names of a taxonomy without links. Rather then using get_the_term, and then looping through the names, like in the function above, I just ran strip_tags() and got the HTML that I was looking for. Boom!

[php title=”Strip tags from taxonomy list”]
echo strip_tags( get_the_term_list( get_the_ID(), ‘location’ ) );
[/php]

Any other taxonomy tricks?

Author: Jake Spurlock

Jake is a geek, designer, HTML+CSS lover. Taker of photos, and sometimes skiing and biking... He spends his time day dreaming new WordPress themes and camping with the Boy Scouts. For some random posts, check out the link blog.

Leave a Reply

Your email address will not be published. Required fields are marked *