Introducing WordPress 3 Custom Taxonomies

Introducing WordPress 3 Custom Taxonomies

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

Category Example

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

Tags Example

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

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

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:

Learn more about add_action.


Adding Classifications to the New Taxonomy

Viewing taxonomy classifications

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.

Adding taxonomy classifications

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

Creating post with classifications

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.

Taxonomy info on single posts

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.

Taxonomy info on single posts 2

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.

Taxonomy Archive Page

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!

Tags: Wordpress
Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • mfrerebeau

    Hello,

    Good tuto.

    Just one thing :

    printf( __( ‘Posts classified under: %s’, ‘twentyten’ ), ” . $term_name . ” );

    should be written as :

    printf( __( ‘Posts classified under: %s’, ‘twentyten’ ), ” . $term->name . ” );

    no ?

  • http://www.ruturaaj.com Ruturaaj

    When it comes to listing the terms of Taxonomy, it all works well in front-end (the actual website pages, like page, single, index etc). But I’m not able to make it work in functions.php file. Can you please tell me how can I fill an array with the terms of Custom Taxonomy which I can use to populate a drop-down in my theme options?

    • Humble Humans

      i am desperate to find out this same answer my friend did you ever figure it out? I’m not trying to populate a menu but i am trying to retreive terms from a custom taxonomy and use them in functions.php to populate an array.

  • http://8biits.com/ Technology News

    Thanks for give me tutorial of wordpress version 3. I think this is best way to know about wordpress.

  • Serg

    Easy way to create custom taxonomy http://obodyanskyy.com/wp_custom_taxonomy

  • http://www.webmarketing-greece.com Lenia

    Thank you so much for this post. FOr me, taxonomies were very complicated and after reading this one I understood the principle. I followed the examples but I have used the arras theme which is a little bit different than the twentyten. So I didn’t manage to display taxonomy classifications. But I followed all the steps before that. I am glad to have found your post.
    Lenia

  • Greg Smith

    This is great info, I hope to use this in the future. I’m also looking to do something even simpler than this, but can’t find the right method anywhere. I want to display, in each post’s byline, its category THEN sub-category (if it’s also in a sub-cat). But WP just shows all categories of the post, in ALPHA order, instead.

    So if my post is in the category “Software” & sub-category “Mac,” it will say “Posted in Mac, Software” because that’s the proper ALPHA order. I’d like it to read “Posted in Software > Mac” to follow the Category > Sub-Category logic.

    Is this easy to do?

  • http://jssolichin.com Jonathan Solichin

    Wonderful article, thank you. It helped me make a site for my client.

  • GRnGC

    Great tutorial, covering the both front & back ends. Thank you!

    I’ve read a lot of articles about custom taxonomies and how great they are, using them it can improve the CMS part of your WP powered website …. but still, there’s one question remained unanswered:

    What about using custom tax on categorized classic posts?

    How can I display separate taxonomy pages, by post category ? and where to set the slug?

    I have posts about more locations categories, and a taxonomy for spoken language in that place
    I’ve set the slug ‘spoken_lang’ and now I wonder if I can use something like:
    …/category/spoken_lang/English/
    to show me all the places where the english is spoken but still in the castle category.

    Yes, having an old fashioned WP site with custom fields and all set for good functionality. I’ve decided to replace some custom fields with custom tax. All works great. (there are some plug-ins that does the hard work for you)… Let me be more specific:
    I don’t use custom types, only categorized posts. Now that the new tax is grouping my posts, I want to be able to “break” this grouping by category, not by custom type.

    I hope I haven’t flooded my question with too much details.
    Thanks again.

  • Lorenzo

    Hello everyone, I have a template where there are the custom taxonomies and would like to make sure that the plugin wp-user-frontend can also interact with these taxonomies, the plugin Wp-user-frontend does is create a form from which users can post articles without accessing the dashboard of wordpress (private area). As for the custom fields plugin allows you to set custom fields, but not for taxonomy and I want to implement this feature, using the taxonomy already created by the template. How can I do? At this address http://tareq.wedevs.com/2012/04/how-to-extend-wp-user-frontend/ I found some information about how to modify the plugin, but I could not implement this feature …
    Help me!! :)

  • http://wpclases.wordpress.com Amit

    Great post,

    Wanted to ask – how can I show in the loop only the posts with a certain taxonomy ?

  • http://mdhmotors.com martin hand

    one important thing you should tell visitors about this tutorial is to visit the permalinks page in admin
    section to flush your re-write rules or the custom taxonomy page/post will not display. I wouldnt assume that everybody would just know this.

    MAKE SURE TO VISIT PERMALINKS IN ADMIN OR TAXONOMY WILL NOT DISPLAY

  • Alex

    This is a great tutorial!

    I’m having trouble with using custom taxonomies in my theme menu. They show up as options to add to the menu, but when clicking “add to menu”, nothing returns.

    Any ideas?

  • http://ablog.gratun.am artak

    thanks. this is very usefull.

  • alex

    I am not able to do the “Displaying Taxonomy Classifications on Individual Pages” part

    1st of all my twenty-ten theme’s single.php dose not have and

    , those two lines are listed under the file named “loop-single.php”
    by following instructions I am getting the result of :

    Parse error: syntax error, unexpected ‘endwhile’ (T_ENDWHILE) in C:\xampp\htdocs\wordpress\wp-content\themes\twentyten\loop-single.php on line 105

    my code looks like this:

    ID, ‘operating_system’, ‘Operating System(s): ‘, ‘, ‘, ” );
    if ( ” != $price_list ) {
    $taxo_text .= “$price_list\n”;
    }

    if ( ” != $taxo_text ) {
    ?>

    can someone please help me by putting the complete code as example or tell me what went wrong?

  • Teresa

    Hello!

    Excellent tutorial I’ve gone crazy looking for something similar. Sorry for my english, it’s very bad.

    But I need help, I need to create a filter with taxonomies, ie to filter by multiple fields: amount of ram + drive + cpu .. not if I explain, I searched a lot but I can not get anything to work. I’m no expert in programming but I try. It’s for a draft animal protection to do multiple searches. Someone could help me? lots thanks!

  • RonStrilaeff

    I’m not sure if anyone from tutplus is reading this anymore, but do you guys know of an easy way to un-register a taxonomy and automatically delete all the test values and terms and post relationships that are now scattered in the database?

  • http://www.facebook.com/maksim79 Maksim Tikhonov

    Thank you very much! What’s a quite nice thing custom taxonomy!

  • brotmaschine

    Thank you!
    Nice to know for building a knowledge base Theme ;)

  • http://www.searchmarketingcontent.com/ Robin Solanki

    Thanks a lot for this tutorial it is very helpful.

  • Novica

    Author is a MAC fan :) :D

  • pascal

    Thanks for this tutorial it is great but I would like to know if there is an easy way to modify the UI so instead of the default Category interface I could have a simply dropdown. Thanks