Adding Metadata to Taxonomy Terms

One feature that makes WordPress a highly flexible and powerful content management system is its implementation of taxonomies. By default, WordPress ships with the “category” and “post_tag” taxonomies. WordPress allows you to set the following metadata for each term in a taxonomy by default:

  • name
  • slug
  • parent
  • description

With the implementation of the add_metadata function in WordPress 2.9, a developer can add any metadata that s/he may desire. This tutorial will teach you how to add metadata for terms by walking you through an example of adding an image url as metadata for “category” terms.

The Foundation

WordPress 2.9 added the following functions to the WordPress core in order to allow for the addition of metadata to objects other that posts.

While it may seem that you simply fill in the arguments for these functions and the metadata will be added, there is a little more involved than that. If you visit the WordPress Codex page for the add_metadata function, it explains that you must first add a new table to the database in order for these functions, when used with taxonomies, to properly store and access data. Fortunately, there are a number of developers who have released plugins that will do this for you, and in most instances, they provide simple wrapper functions to make adding term metadata quite simple. The plugin that I use for this task is Simple Term Meta, lovingly coded by Jacob M. Goldman. This plugin will add the needed table to your database and gives you the following functions (among others) for your use.

  • add_term_meta
  • update_term_meta
  • get_term_meta

Yes, those functions look very similar to the WordPress functions mentioned earlier. These functions are merely wrapper functions that remove the need to declare the “meta_type” parameter for each call to the metadata functions. Additionally, these functions operate in a similar fashion to the post metadata function (i.e., add_post_meta, update_post_meta, get_post_meta). In fact, just as the term metadata functions are wrappers for the WordPress metadata functions, so to are the post metadata functions.

Make sure to install the Simple Term Meta before proceeding with this tutorial as the rest of it will not work without it installed.

Creating Form Inputs on Categories Page

In order to add information to the database, form inputs need to be created. The form inputs will be added to the following two screens:

  1. Add category page (e.g., yourdomain.com/wp-admin/edit-tags.php?taxonomy=category)
  2. Edit category page (e.g., yourdomain.com/wp-admin/edit-tags.php?action=edit&taxonomy=category&tag_ID=4&post_type=post)

To accomplish this task, add the following code to your theme’s functions.php file (or to a plugin file).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?php
add_action('category_add_form_fields', 'category_metabox_add', 10, 1);
add_action('category_edit_form_fields', 'category_metabox_edit', 10, 1);	
 
function category_metabox_add($tag) { ?>
	<div class="form-field">
		<label for="image-url"><?php _e('Image URL') ?></label>
		<input name="image-url" id="image-url" type="text" value="" size="40" aria-required="true" />
		<p class="description"><?php _e('This image will be the thumbnail shown on the category page.'); ?></p>
	</div>
<?php } 	
 
function category_metabox_edit($tag) { ?>
	<tr class="form-field">
		<th scope="row" valign="top">
			<label for="image-url"><?php _e('Image URL'); ?></label>
		</th>
		<td>
			<input name="image-url" id="image-url" type="text" value="<?php echo get_term_meta($tag->term_id, 'image-url', true); ?>" size="40" aria-required="true" />
			<p class="description"><?php _e('This image will be the thumbnail shown on the category page.'); ?></p>
		</td>
	</tr>
<?php }	?>

Taking a closer look at this code, the first two lines instruct the two functions that add the form inputs to be called at the bottom of the category add and edit screens. The category_add_form_fields hook is called in the add category screen (e.g., yourdomain.com/wp-admin/edit-tags.php?taxonomy=category), and the category_edit_form_fields hook is called in the edit category screen (e.g., yourdomain.com/wp-admin/edit-tags.php?action=edit&taxonomy=category&tag_ID=4&post_type=post). Notice that the first word in the hooks is “category”. The first word in the hook specifies the taxonomy in which this hook is run. If the target taxonomy was named “location”, the proper hooks would be location_add_form_fields and location_edit_form_fields.

In the present code, different functions are being sent to the different hooks. Unfortunately, the layout of the add and edit screens for taxonomies have very different markup, so the same function cannot be used for both hooks. For the category_metabox_add function, a text input with name “image-url” is added. The markup is taken straight from WordPress core in order to match the styling of the other fields. This code gives us the following:

Enhanced add category screen

In addition to adding an input on the add category page, a corresponding input needs to be added for the edit category page. Like with the add category page, I dipped into the WordPress core and utilized the code that generated the other fields in order to get a similar look for the new input field. You will notice that it’s presented in a table instead of a div structure. Presumably, when the edit screen is accessed, there will already be data entered for the field. In order to show that data, it needs to be accessed from the database. This task is accomplished with the use of the get_term_meta function, one of the functions made available by the Simple Term Meta plugin. The function is defined in the plugin with:

1
get_term_meta( $term_id, $key, $single = false )

The “term_id” is the id given to the term when it is first entered into the database. The “key” is the name of the metadata. “Single” specifies whether to return an array (single = false) or a string (single = true). In order to get a value if one has already been entered, the following code is utilized.

1
get_term_meta($tag->term_id, 'image-url', true);

“$tag” holds the term object, thus making the id for the tag obtainable with “$tag->term_id”. Next, ‘image-url’ is specified for the key as it is what I would like the metadata to be called. The function that displays the input for the edit screen will give you something like the following image.

Enhanced edit category screen

Now that the input fields are set up, it is time to write some code that will add the values to the database when submitted.

Saving Term Metadata

Adding the metadata to the database is quite straight forward when utilizing the functions provided Simple Term Meta. It can be done with the following code.

1
2
3
4
5
6
7
8
add_action('created_category', 'save_category_metadata', 10, 1);	
add_action('edited_category', 'save_category_metadata', 10, 1);
 
function save_category_metadata($term_id)
{
    if (isset($_POST['image-url'])) 
		update_term_meta( $term_id, 'image-url', $_POST['image-url']);         			
}

To begin, the save_category_metadata function is called using two special hooks. The created_category hook is run when the category is initially added and the edited_category hook is run when the category is edited. Like the hooks used in adding the input fields to the form, these hooks can be changed for a custom taxonomy. If the taxonomy was “location”, the hooks would be changed to created_location and edited_location.

The save_category_metadata is very simple. It checks to see if the “image-url” key in the $_POST array is set. If so, the metadata is added using the update_term_meta function. The update_term_meta is defined in the Simple Term Meta plugin as:

1
update_term_meta( $term_id, $meta_key, $meta_value, $prev_value = '' )

The “term_id” and “meta_key” parameters specify the id of the term that the metadata is associated with and the name of the metadata, respectively. The “meta_value” parameter specifies value of the metadata. In the present example, the following code is used to enter the metadata.

1
update_term_meta( $term_id, 'image-url', $_POST['image-url']);

The “term_id” is magically passed to the function using by the hook. Therefore, the “term_id” is simply thrown into the function. Because I want the metadata saved using the “image-url” key, I set that as the second parameter. Finally, the third parameter is set as the value of the field input, which is accessed using $_POST['image-url']. Upon saving the taxonomy, the values are saved to the database and can be accessed using get_term_meta, which will be demonstrated in the next section.

Using Term Metadata in a Theme

Fields have been added to the “category” taxonomy screens and the data has been saved. All that is left is using this data in some interesting way. Since I currently have the second beta of WordPress 3.2 installed on my development setup, I will demonstrate using term metadata in the brand new “Twenty Eleven” theme.

On the default category page, the theme displays the category name, description, and begins showing the posts in that category. It looks like the following screenshot.

Category page without metadata

Inserting the following code into “category.php” displays the image specified in the term metadata on the category page.

1
2
3
4
<?php $thumb_src = get_term_meta(get_query_var('cat'), 'image-url', true); ?>
<?php if($thumb_src != '') : ?>
	<img src="<?php echo $thumb_src; ?>" width="50" height="50" style="float:left; margin-right: 10px;" />
<?php endif; ?>

The get_term_meta retrieves the value previously saved in the database and returns it for use in the template. Using the value for the “src” attribute in the “img” tag allows the image to be displayed. This results in a slightly more “graphic” category page.

Category page with metadata

Conclusion

As one can see, adding metadata to terms is not a difficult task. With an excellent plugin like Simple Term Meta, WordPress can be extended to manage more data associated with taxonomy terms. If you have any experience with the WordPress post metadata functions, you are already familiar with how the term metadata functions work. The most important aspects to remember when dealing with term metadata is that term metadata does not work “out of the box.” It is absolutely necessary that the proper addition to the database is made. Additionally, you must make sure that you utilize the proper hooks to add input fields to the add and edit screens, as well as when saving the data. If you follow those steps, you will be on your way to creating all of the term metadata that your heart can desire.

This article was authored by:

I am a Senior Web Engineer at 10up LLC. While I am well versed in general web development, WordPress is my bread and butter. I enjoy working on WordPress projects, writing plugins, and helping other learn about appreciate how incredible the WordPress software is. After about 8 years doing web development, I have finally launched my own website. I’d like to think it’s because I finally feel that I have something to say, but really, it’s actually because I was finally able to design a theme that I did not loathe.

Zack Tollman has authored 6 posts.Visit Website

Showing 11 Comments

  • Hi Zach, I’m trying to get this working however I can’t seem to input the first part of the code into my functions.php file without it breaking. I then tried to add it to a simple plugin but it fails to activate. Is there something else supposed to be added into the overall php script to make it work?

    Many thanks,

    Harry

    REPLY
  • Zack Tollman (Admin)

    @Harry,

    Are you being mindful of the opening and closing php tags. If not, that might throw an error. Also this code will only work with the Simple Term Meta plugin installed.

    If this didn’t help, can you pastebin (http://pastebin.com/) your code and I’ll take a look at it.

    REPLY
  • WOW, simply, WOW !!!
    Wish I had the skills to merge this with league manager’s wordpress plugin in order to build each player’s file from a team’s roster.
    Will come back here 4 sure.
    THANK YOU

    REPLY
  • Zack Tollman (Admin)

    Jose,

    Thanks for the great response! I just took a look at the League Manager plugin, and, unfortunately, it looks like this tutorial won’t be of much help to you. League Manager does not utilize any taxonomies and as a result, adding term meta to it is not necessary.

    Best of luck turning League Manager into a plugin that works for you!

    REPLY
  • great article. really helped me out!

    REPLY
  • Zack Tollman (Admin)

    Thanks Alex! Term meta really opens up a lot of possibilities and helps keep data nicely organized. I’d be interested in hearing what you do/did with it.

    REPLY
  • This is breaking for people because there is a typo in your first section of code. The second add_action function (the one that hooks to the edit function) has an extra closing parenthesis

    add_action(‘category_edit_form_fields’, ‘category_metabox_edit’), 10, 1);

    Remove that and things should run smoothly :) And thanks for the great fix! I’ve been looking all morning for something like this!

    REPLY
  • Zack Tollman (Admin)

    Thanks for pointing out the typo Bobby! I’ll have the editor fix it up!

    Glad you found this article useful!

    REPLY
  • schizdazzle

    I’ve noticed in the edit function <input name="image-url" id="image-url" type="text" value="term_id, ‘image-url’, true); ?>” size=”40″ aria-required=”true” />

    the “value” causes the page to break… is there any reason why it is? (i did my own version first and then tried yours as an exact copy and it still didn’t work)

    REPLY
  • It’s worth pointing out that the Simple Term Meta plugin is actually included in the Custom Taxonomy Sort plugin – so if you have that plugin installed, you already have the termmeta table and relevant functions available.

    REPLY
  • Really very helpful to me.
    It saved my time.

    REPLY

Add Your Voice: