Tutorial Details
- Program: WordPress
- Version: 3.0
- Difficulty: Intermediate
- Estimated Completion Time: 20 Minutes
WordPress 3 fills in a number of important gaps towards being a serious content management system. The easy-to-use custom taxonomies function gives site designers some powerful tools for building a good information architecture. Learn what taxonomies are, why they’re useful, and how to use them in today’s tutorial!
What is a Taxonomy?
Taxonomies are different methods for classifying things.
Taxonomies are different methods for classifying things. This tutorial uses an example of posts about different desktop computers, which can be classified by a number of distinct criteria, including:
- Amount of RAM
- Size of hard drive
- Speed of CPU
- Type of CPU
- Operating system installed
- and so forth…
A Brief History of WordPress Taxonomies
Categories
Prior to version 2.3, WordPress had only one generic taxonomy, called Category, for Posts. This worked well for blogs, as you could create a top-level category called “Desktop Computers,” with a subcategory called “RAM,” which may have subcategories such as “Less than 1 GB,” “1 GB,” “2 GB to 4GB,” and so on. A second child category of “Desktop Computers” might be called “Operating System,” with subcategories such as “Windows XP,” “Mac OS,” “Red Hat,” “Ubuntu,” and so forth.
When a system allows you to have categories that can be divided into subcategories, we call it a hierarchical structure. The best you could do for a serious site architecture prior to WordPress version 2.3 was to create a large hierarchy of categories, where the top level categories represented large taxonomy groups.
Tags
Version 2.3 of WordPress added another type of taxonomy called Tags. While categories are usually thought out in advance, specific to the types of content on a site, tags provide a more freeform, impromptu method of classifying content.
For instance, when writing a Post about a particular desktop computer, tags allow the author to type one or more keywords such as “gaming,” “tivo,” “noisy fan,” and so forth. These keywords might not make sense as site-wide categories, but help provide some additional classification to a post. Site visitors could then easily find all the posts tagged with “noisy fan” later. The freeform nature of tags, however, doesn’t help us build a solid classification system around known values such as operating system types or CPU types. Tags are also one-dimensional, not allowing any hierarchical structure.
Single-Level Custom Taxonomies
WordPress version 2.8 made it possible to add custom classification schemes with just a few changes to the code on your site. This allowed you to build a list of possible operating systems, separate from a list of possible RAM types, and so on. It did not, however, allow these custom taxonomies to be built in a hierarchy similar to the generic categories taxonomy.
Fully Hierarchical Custom Taxonomies
Finally, WordPress version 3 gives us fully hierarchical custom taxonomies. Notice how the hierarchical nature allows us to simplify the Operating System taxonomy, for instance, by pushing all the different Windows variants under a “Windows” parent classification. This will allow visitors to see all posts classified with any Windows operating system, or allow them to be more specific and see only posts classified with Windows XP, for instance.
Creating a Custom Taxonomy
Editing your theme’s functions.php file
WordPress version 3 does not allow you to create custom taxonomies from the administration screen. To initially define your custom taxonomies without a plugin, you’ll need to add a little bit of code to your theme’s functions.php file. This isn’t too difficult — just follow my lead.
To add custom taxonomies, we need to edit the “functions.php” file found inside your theme directory. For instance, I’m using the default “twentyten” theme that comes with WordPress 3.0, and my WordPress installation is in a directory named “wp.” My functions.php file is then at:
[website_root]/wp/wp-content/themes/twentyten/functions.php.
Adding the Taxonomies in Code
We’ll stick with the Desktop Computer example, adding separate taxonomies for RAM, Hard Drive, and Operating System. At this point, we’re simply adding the taxonomies themselves, like empty containers. Fortunately, we can add and manage the different classifications, such as “Windows XP,” from the comfort of the admin dashboard.
Step 1 One Function to Create Them All
First, we need to build one function that creates all the taxonomies we need. We’ll call the function “build_taxonomies.” Let’s add this function to the bottom of the functions.php file.
function build_taxonomies() {
// code will go here
}
Step 2 Defining the Taxonomies
Next, for each taxonomy we want to create, we need to call a particular WordPress function with the right parameters. Here’s the function, and its important parameters explained.
register_taxonomy(
'internal_name',
'object_type',
array(
'hierarchical' => {true|false},
'label' => 'Human Readable Name',
'query_var' => {true|false},
'rewrite' => {true|false}
)
);
- internal_name: What will this taxonomy be called from inside WordPress, in the database and template files?
- object_type: Which types of content can be classified with this taxonomy? Possible values are “post, page, link,” and then names of custom post types we’ll learn to create in a future tutorial.
- Next comes an array of optional parameters. We’ll use the most important ones here in this tutorial, but a full list can be found on the Function Reference / register_taxonomy Codex page. The parameters we’ll use are:
- hierarchical: If ‘true,’ this taxonomy has hierarchical abilities like WordPress Categories. If ‘false,’ this taxonomy behaves much like freeform Tags.
- label: This is the human-readable name used in your site’s interface to label the taxonomy.
- query_var: If ‘true,’ we’ll be able to ask WordPress for posts dependent upon the selections for this taxonomy. For example, we could search for all the posts where the operating system taxonomy has ‘Windows’ selected.
- rewrite: If ‘true,’ WordPress will use friendly URL’s when viewing a page for this taxonomy. For example, a page listing all the posts with the “Windows” operating system selected would be represented by the following url: http://domain.com/operating_system/windows
Our entry specific to adding the Operating System taxonomy looks like so:
register_taxonomy( 'operating_system', 'post', array( 'hierarchical' => true, 'label' => 'Operating System', 'query_var' => true, 'rewrite' => true ) );
Go ahead and add that to your “build_taxonomies” function.
More information:
“register_taxonomy” is further defined within the WordPress codex.
Step 3 Calling the Taxonomy-Creating Function
We need to add one more line to the “functions.php” file so our “build_taxonomies” function will actually be executed. We’ll “hook” the “build_taxonomies” function to the “init” event by adding the following code:
add_action( 'init', 'build_taxonomies', 0 );
You can add this line anywhere, but I generally add it above the function we’re calling, so it would look like this:
// Custom Taxonomy Code
add_action( 'init', 'build_taxonomies', 0 );
function build_taxonomies() {
register_taxonomy( 'operating_system', 'post', array( 'hierarchical' => true, 'label' => 'Operating System', 'query_var' => true, 'rewrite' => true ) );
}
More information:
Adding Classifications to the New Taxonomy
Once you’ve added the “Operating System” taxonomy to the “functions.php” file correctly, it should show up as a new item in the “Posts” panel of your dashboard. Click the taxonomy’s name to add and edit the classifications you want to include.
Now, you can add and edit Operating Systems just as you would add generic Categories.
Adding More Taxonomies
If you want to add the “RAM” and “Hard Drive” taxonomies to follow along with the example, just add the following to your functions.php file:
register_taxonomy( 'ram', 'post', array( 'hierarchical' => true, 'label' => 'RAM', 'query_var' => true, 'rewrite' => true ) ); register_taxonomy( 'hard_drive', 'post', array( 'hierarchical' => true, 'label' => 'Hard Drive', 'query_var' => true, 'rewrite' => true ) );
Once finished, the changed section of your functions.php file will look something like this:
// Custom Taxonomy Code
add_action( 'init', 'build_taxonomies', 0 );
function build_taxonomies() {
register_taxonomy( 'operating_system', 'post', array( 'hierarchical' => true, 'label' => 'Operating System', 'query_var' => true, 'rewrite' => true ) );
register_taxonomy( 'ram', 'post', array( 'hierarchical' => true, 'label' => 'RAM', 'query_var' => true, 'rewrite' => true ) );
register_taxonomy( 'hard_drive', 'post', array( 'hierarchical' => true, 'label' => 'Hard Drive', 'query_var' => true, 'rewrite' => true ) );
}
Creating a Post Using your New Taxonomy
Create a few new posts, and you’ll see your new taxonomy options appear in the Edit Post screen. Select whatever classifications you feel apply to your posts.
Showing a Post’s Various Taxonomies
Nothing we’ve done so far can be seen by your site visitors. We’d like for posts to show what custom taxonomies they’re classified in, just like posts commonly reveal their categories and tags.
To do so, we only need to make a simple addition to the loop in certain template files.
Displaying Taxonomy Classifications on Individual Pages
In the twentyten theme, and many others, a post’s categories and tags are listed below the body text. We’re going to add custom taxonomy information, if it exists, just before the category and tag information.
To make this happen, we’ll need to edit the “single.php” template file, which is normally called to display an individual post. My single.php file is at: [website_root]/wp/wp-content/themes/twentyten/single.php.
Step 1 Find the Right Place to Add Code
In single.php, find the line with:
<div class="entry-utility">
This appears just before the:
<div id="nav-below">
In twentyten, this div contains the categories, tags, permalink, and other data for the current post. We’ll put our taxonomy information just above this div.
Step 2 Retrieve Taxonomy Information About the Current Post
Populate some variables for holding the taxonomy information output and the different taxonomy information we may expect to find.
<?php // Let's find out if we have taxonomy information to display // Something to build our output in $taxo_text = ""; // Variables to store each of our possible taxonomy lists // This one checks for an Operating System classification $os_list = get_the_term_list( $post->ID, 'operating_system', '<strong>Operating System(s):</strong> ', ', ', '' );
Here, we’re calling the WordPress function “get_the_term” list with the following parameters:
- $post->ID : the id of the current post.
- ‘operating_system’ : the name of the custom taxonomy we’re checking for data. We’re asking if the current post has been given any classifications in the ‘operating_system’ taxonomy.
- ‘Operating System(s)’ : If anything is returned, this is the string we’d like to have in front of it.
- ‘, ‘ : If multiple items are returned, this is the string we’d like to have them separated by.
- ” : If anything is returned, this is the string we’d like to have behind it. In this case, we want nothing added behind the result.
We’ll do the same for the other two taxonomies we might expect to contain data:
$ram_list = get_the_term_list( $post->ID, 'ram', '<strong>RAM Option(s):</strong> ', ', ', '' ); $hd_list = get_the_term_list( $post->ID, 'hard_drive', '<strong>Hard Drive Option(s):</strong> ', ', ', '' );
More information:
Learn more about “get_the_term_list.”
Step 3 Format Results from Classifications, if Any
Check for results in each of the three possible taxonomies. If they exist, add them to our output, as well as a linebreak.
// Add OS list if this post was so tagged
if ( '' != $os_list ) {
$taxo_text .= "$os_list<br />\n";
}
// Add RAM list if this post was so tagged
if ( '' != $ram_list ) {
$taxo_text .= "$ram_list<br />\n";
}
// Add HD list if this post was so tagged
if ( '' != $hd_list ) {
$taxo_text .= "$hd_list<br />\n";
}
Step 4 Display Classification Results, if Any
Check to see if the above steps resulted in any taxonomy information at all to output. If taxonomy info exists, we’ll output it wrapped in a div of class “entry-utility.”
// Output taxonomy information if there was any
// NOTE: We won't even open a div if there's nothing to put inside it.
if ( '' != $taxo_text ) {
?>
<div class="entry-utility">
<?php
echo $taxo_text;
?>
</div>
<?
} // endif
?>
Step 5 Check Your Results
Visit a post page, and you should see any custom taxonomy classifications listed below.
Viewing a List of Posts by Taxonomy Classification
Now our individual posts tell us what custom taxonomies they have been classified with. When they list a custom taxonomy classification, they also provide a link to list all posts under that classification. For instance, clicking the “Mac OS” link next to “Operating Systems” under our post will theoretically list all the posts with the “Mac OS” operating system classification.
However, this doesn’t happen out of the box with WordPress version 3. We’ll have to make a custom template file for displaying taxonomy archives in order for it to work. WordPress already lets visitors view all posts assigned to a particular category, or all posts given a certain tag. When we’re done here, we’ll be able to view all posts assigned to particular classifications in our custom taxonomies, too.
To make this happen, we’ll need to create the “taxonomy.php” template file. WordPress will try to use this file any time it wants to list posts in a custom taxonomy.
Step 1
Open the “category.php” file, copy its contents, and paste it into a new file called “taxonomy.php.” Save taxonomy.php in the theme directory. For instance, my taxonomy.php file is at:
[website_root]/wp/wp-content/themes/twentyten/taxonomy.php.
Step 2 Get Information About Current Taxonomy Classification
In the taxonomy.php file, we need to get information about the taxonomy being listed. We’ll probably want the name and description (if any) for the selected classification.
Just under <?php get_header(); ?>, add the following line:
$term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) );
This gets all of the information about the taxonomy that called this page and returns it as an object into the variable $term. For example, the “Mac OS” classification returns an object as such:
stdClass Object
(
[term_id] => 13
[name] => Mac OS
[slug] => mac-os
[term_group] => 0
[term_taxonomy_id] => 22
[taxonomy] => operating_system
[description] =>
[parent] => 0
[count] => 2
)
Step 3 Display Classification Name and Description
We want to change the page name to tell visitors what they’re looking at. Since we started with the category.php template, we can take the line that used to print the category name and change it a bit to give us our desired page name and, if applicable, description.
Change the following line from category.php:
printf( __( 'Category Archives: %s', 'twentyten' ), '<span>' . single_cat_title( '', false ) . '</span>' );
To read as follows:
printf( __( 'Posts classified under: %s', 'twentyten' ), '<span>' . $term_name . '</span>' );
This changes the static text beginning the line, and then inserts the name of the classification. (Note: for proper localization, we would need to add ‘Posts classified under:’ correctly to the languages/twentyten.pot file. That’s outside the scope of this tutorial, but be aware of the transgression here.)
Then add the following:
if ('' != $term_descr ) {
echo "<p>$term_descr</p>\n";
}
If a description exists for this classification, it will be displayed just beneath the title.
After making changes to taxonomy.php, visit one of your posts that has been given a custom taxonomy classification. Because of our earlier work in the file “single.php,” the post should show custom classifications below it. Simply click one of those classifications to see the taxonomy listing at work.
Conclusion
I hope this tutorial explained clearly what taxonomies are and showed you how to make use of them in WordPress 3 as a powerful organizational tool. I hope to provide a follow up tutorial soon explaining WordPress custom post types, their tight relationship with custom taxonomies, and how to use them. Thanks so much for taking the time to visit Nettuts!


RoyalSlider – Touch-Enable ... only $12.00 
Wow ! Great article ! )) Thanks a lot
Hi,
Surely its a great tutorial. It explains about taxonomy and how to use it. Kindly explain what are the benefits of this feature, why should I use it.
Just for try or more then that is there??
He explained how it would benefit a computer review site. In my opinion, the most obvious benefit is organization.
For example, I could create a website for musicians where they could browse and search for guitars, amps, mics, etc. The user could view all guitars or view only electric guitars or view only 7-string electric guitars. This would be extremely beneficial if the user already new what kind of guitar he was looking for.
Excellent new feature, great article! Can’t wait to try it out, cheers!
Is there difference between the word “category” and “Taxonomy”?
Mohamed: I consider “Category” as a smaller, generic part of an overall “Taxonomy.”
In my opinion, I think it’s best to consider “Taxonomy” as the overall structure of a body of information. Defining a taxonomy such as “Color,” “Artist,” “Genre,” etc. is more specific than lumping those classifications under a hierarchy in “Category.”
With that additional specificity, you can begin to build a more powerful site, offering faceting (e.g., narrowing your search results as on bestbuy.com,) more granular search abilities, and guiding your site contributors more with custom post types.
Stay tuned to nettus.com, as I plan to cover Custom Post Types very soon, and Faceting in the near future.
Faceting: http://en.wikipedia.org/wiki/Faceted_search
Very helpful. Thanks.
Does WordPress 3.0 support faceted browsing/searching? If so, I’d love to see a tutorial on that. Does it require a plugin? If so, is there one you’d recommend?
Category is essentially a Taxonomy for Posts in WordPress. Tags would be another taxonomy for posts.
Thanks, It was helpful.
Great article. Thanks.
Can’t wait to read the custom post tutorial. I heard a little about it, and its sound really interesting to me.
Great features coming in WP3 :-)
Hi!
That’s great!
I can’t wait for the next tutorial!!!!
I’m blown away, very thorough and comprehensive roundup. Let me bookmark and retweet it!
Very well written article. I was exploring the WP 3.0 custom taxonomies in detail myself, so this is pretty informative.
Excellent, thanks for this clarification!
Another great tutorial.
Many thanks!
Let’s make all the web WordPress.
Ah, no… let’s not.
I really hate WordPress.
With 3.0, WordPress is becoming more and more one of the best open source CMS out there.
Now, a faceted search for custom taxonomies would be a great plugin.
A agree with this!
Custom taxonomies also works for pages and custom post types. However, there seems to be a bug for me in WP3 that prevents the admin UI from showing up for custom taxonomies applied to pages (it shows for custom post types).
Any suggestions or does it work for you guys?
Stephen: At this point, it depends on what nightly build you’re using. 3.0 is literally bleeding edge right now. While building the Taxonomy tutorial, the whole process broke for me a few times!
Once version 3 is officially released, I hope to do a tutorial on custom post types, and include a bit about using it for pages as well.
Good tutorial and useful introduction tu WP3 :) Thanks a lot.
Great feature and article! Thanks for the information mate!
Great article, very detailed! Thanks for all this information.
Основательно так расписал! WordPress рулит!
very nice tutorial thanks lot
Great article. Looking forward to trying it out
This new features are looking quite sweet. I love using WordPress and would always recommend it.
Can anyone shed some light on how to best set meta title and descriptions for custom taxonomies..? That doesn’t seem so simple.
The next thing now would be to work through how adding posts / pages to specific taxonomies can be restricted by role (editor / author).
That was a great article and I really love the direction WordPress is going. I love WordPress and this just gives me more reason to use this as a fully fledge CMS platform.
Sooo looking forward to WordPress 3.0!
WordPress is great, I’m going to start offering it to all my clients. I started building my own CMS, got halfway done, then realized WordPress has everything I would want in a CMS plus an active community = continued improvements.
Great post! WP 3.0 is going to be great, I can’t wait to utilize this: http://kovshenin.com/archives/custom-post-types-in-wordpress-3-0/
While this is a fantastic overview on the topic – I would like to see your take on it in conjunction with Custom Post Types. I’ve been playing with them both, and that’s really where the power shines.
Jeffikus: Agreed. My next tutorial is on Custom Post Types, and leverages this Custom Taxonomies tutorial. Stay tuned!
Probably asking a lot here, but when you write your tutorial on post_types leveraging custom taxonomies, I have a request.
If you register a taxonomy to multiple post_types, you will end up with an interesting ‘issue’ on the custom taxonomy index page. Namely, it will list all the posts that belong to the custom taxonomy. Of course that is how it should be.
However, it would be really great to combine multiple loops to be able to separate out the post_types when viewing the custom taxonomy index.
scenario:
I create custom taxonomy genre and apply that to custom post types ‘movies, books, music’.
my ‘genre’ taxonomy index page is going to show all of those post types jumbled together according to post date with no discernible separation of post_type. A reader can’t tell by looking which link is a movie, book, or music.
Calling multiple loops, one for each post_type (with pagination) would allow us all to style them differently, making it much easier for the reader to grasp.
kinda advanced, but would be nice to figure out.
thanks
Any idea on when WordPress 3.0 is coming out ?
WordPress 3.0 really looks sleek and rocks. I am really excited about this kind of articles.Great
thx!!! so much.
Someone is talking about Drupal?
Great Tips, Thanx
Great tutorial. I’ve known about custom taxonomy via a post of Justin Tadlock, but this post is more comprehensive. This is “must-read” for every WordPress developer. With custom taxonomy, custom post types, I think WordPress is growing as a real CMS for not only blog or simple sites, but also for complex sites, too.
This is beyond awesome!
Awesome, awesome, awesome! Been looking for a post like this for the last few weeks as I’ve been digging into the WordPress 3.0 beta. Thanks so much for your research and effort compiling all this great info.
Sure looking forward to future WordPress posts from ya’ll!
A very clear explanation of the potential benefits of the new taxonomy features – I can already think of a number of places where this could be useful, especially with the new navigation system. Thanks very much.
@NetChaos – I believe it’s slated for the middle/end of summer. I understand there’s some bugs with the new navigation that they’re working on at the moment.
You can get the second beta release from WordPress.org, though, and it’s worth having a look at. The navigation system together with the custom taxonomies and the custom post types are a huge leap forward and I’m really excited about the possibilities.
I’d love to know if a Custom Taxonomy can be SHARED by different content/post types. For example, if I have a Taxonomy for “color” and it has Terms (possible values):
- Red
- Blue
- Green
I would think that any of my content types should be able to use that taxonomy, but it seems that’s not the case. When a taxonomy is registered, it is tied to a specific object. I hope I’m wrong, or I hope there’s a workaround. It seems silly to have to maintain two separate but identical taxonomies for “color”.
I answered my own question, if anyone has the same issue:
http://wordpress.org/support/topic/396701
Very interesting, I love the direction WP is taking.
Would there be a way to tie custom taxonomies to the search itself though? (As opposed to filtering results on the results page)
Really a wonderful tutorial..Thanks alot for the author..
Nice, I can’t wait to use this in WP3, although I’m waiting until the official public version comes out before I try it.
great tutorial!
there is one error.
printf( __( ‘Posts classified under: %s’, ‘twentyten’ ), ” . $term_name . ” );
should be
printf( __( ‘Posts classified under: %s’, ‘twentyten’ ), ” . $term->name . ” );
same for
if (” != $term_descr ) {
echo “$term_descr\n”;
}
should be
if (” != $term->descr ) {
echo “$term->descr\n”;
}
Thanks, this is excellent tutorial, but there is a small mistake in code, on step 3 ” Display Classification Name and Description”.
Right way for display classification name is $term->name instead of $term_name,
@wjm and @dreamhelg: Nice catch, thanks for pointing it out. I goofed that up when formatting the article and can avoid that now in the future.
Take care.
Using just after get_header and <?php printf( __('Posts classified under: %s', 'twentyten' ), '’ . $term_name . ”); ?> within the H1 doesn’t display $term_name in 3.0-beta2-14597.
Did the devs change how this works or am I just missing something?
Nevermind. Please delete my previous comment, I missed the comments above me….
Taxonomies were put to the side when I developed because I could not for the life find an article to describe their definition and purpose that made sense. Found it! Bookmarked it!
It could be valid to state, then, that WordPress should just be used always. Fire all those developers, you can get it for free. Anyone that disagrees, probably nerds themselves out in assembly language…still using JSP to make websites maybe…you know, those guys!
Fantastic tutorial! It is very clear and concise as always, yet another reason I visit this site so often.
One request:
Could you expand on this tutorial to describe how to apply meta data to a taxonomy?
I’ve been struggling to figure out how to apply attributes to my custom taxonomies such as an image and description. (in example above taking about using a picture of a cpu, apple, etc, next to tax name).
To date I have not found this information anywhere in the codex or online. Would be much appreciated.
Doesn’t this sound like adding a new root category ?
What about performance? Doesn’t the rewrite make the .htaccess file even larger now? Does
the taxonomies fix performance issues or complicate things more later?
The URL structure used most often slows down sites with 100′s of pages unless there’s
a numeric field before the post just like archives, like this:
http://sub.yourdomain.com/sub-domain/YEAR/MONTH/Individual-posts-you-make-every-day
http://net.tutsplus.com/tutorials/2010/05/introducing-wordpress-3-custom-taxonomies/
This is how most blogs are set up, post right after category::
http://net.tutsplus.com/tutorials/wordpress/introducing-wordpress-3-custom-taxonomies/
The category should not appear before any of the posts because each post is listed under more
than just one category. That slows WordPress down with all the extra code in the .htaccess file
it has to keep reading.
That started in early 2009 or when 2.6 was released, didn’t it? I don’t use WordPress that much
yet but I know you can’t just change the structure after your blog has 1,000′s of pages. That
would be too messy. I thought WordPress was planning a patch before 3.0 was released? Have
you read the WordPress instructions for setting up the URL permalinks?
I have a need for speed so I’m always concerned with it, that’s all.
This has been a really helpful tutorial, and I am really looking forward to getting stuck into using what I learned on future sites.
I do have one question though, do we think it will be possible to query multiple taxonomies? Using the example from the tutorial, for example if a user wanted to find a windows computer with 2GB RAM and a 80 – 100GB hard drive. Could the user use something like radio buttons to make selections and WordPress could pull up the posts with the matching taxonomies?
http://scribu.net/wordpress/query-multiple-taxonomies
thanks tex88
@Paul: In a few weeks, I hope to show how you can use custom taxonomies to do a faceted search, narrowing down your selections as you might on a retail site. For now, @tex88′s link will allow you to get a custom search solution going.