Saving ‘meta data’ for WordPress categories
By Glenn | February 7th, 2010 | Published in WordPress, development
WordPress has some great hooks for adding extra fields to the Add Category page (as well as the edit category and the table listing the categories). Where / how do you save that data though. I ran accross a couple other devs on Twitter this evening that were asking this question. This post is primarily for them and it doesn’t provide all the code you need to get finish, but it should get most dev on their way. For instance, you will need another action for adding to the edit page, another action for adding to the table, and another action for editing the data.
This shows you how to save the data. I’ll update the post later to provide a complete example.
A couple of disclaimers:
- The hook name changes from 2.9.1 to 3.0 for adding the field to the form… hence the conditional in the code
- If you’re running trunk, the extra field will appear twice because of a bug in the code. I placed a ticket in trac: http://core.trac.wordpress.org/ticket/12171
This following code, placed in your theme’s functions.php file:
// Adds fields to add category screen
function ft_add_category_field(){
?>
<div class="form-field">
<label for="extra"><?php _e('Extra Field') ?></label>
<textarea name="extra" id="extra" rows="5" cols="40"></textarea>
<p><?php _e('The description of the extra field.'); ?></p>
</div>
<?php
}
if ( get_bloginfo('version') < 3 ){
add_action('edit_category_form','ft_add_category_field');
}else{
add_action('add_category_form_fields','ft_add_category_field');
}
// On Insert Category
function ft_created_category($term_id,$tt_id){
// This lets you see the values of the two args being passed in
echo "term_id = ".$term_id."<br />";
echo "tt_id = ".$tt_id."<br />";
// This is the name of your extra fields
echo "extra = ".$_POST['extra'];
// You should now have everything you need to update options.
}
add_action('created_category','ft_created_category',10,2);
Download a text file with the above code: here