Would you like to add new custom fields to your WordPress posts, pages, and categories? Now you can easily do this with the WordPress custom taxonomy system. For example, if you have a blog on movie reviews, you may want to add the fields Actors and Genre to each of your posts.
What is less clear, however, is how you can expand your WordPress admin interface, so that users can easily enter in these new custom fields. WordPress 2.8+ will only include an input interface for custom taxonomies associated with posts. In addition, this input interface is the standard tag interface, where you must type in the new fields as plain text.
If you are looking for a drop-down menu, or a radio button list, you are out of luck.
Here, we consider how you can flexibly expand your WordPress post interface and style your custom taxonomy input panel however you want.
1. Create Your WordPress Custom Taxonomy
First, we create a simple test attribute called theme and we associate it with our WordPress posts. We add three initial terms to our new theme attribute – Beauty, Halloween, and Dragons.
Note that the hierarchical argument simply refers to whether your new theme attribute is a hierarchical structure, such as your WordPress categories, or whether it is flat, such as your WordPress tags.
The hierarchical argument does not currently affect the input interface of your new attribute. As of WordPress 2.8, the normal tag input interface will be used for all custom taxonomy attributes. To restyle the custom taxonomy input interface, you must use the add_meta_box command.
add_action( 'init', 'create_theme_taxonomy', 0 ); function create_theme_taxonomy() { if (!taxonomy_exists('theme')) { register_taxonomy( 'theme', 'post', array( 'hierarchical' => false, 'label' => __('Theme'), 'query_var' => 'theme', 'rewrite' => array( 'slug' => 'theme' ) ) ); wp_insert_term('Beauty', 'theme'); wp_insert_term('Dragons', 'theme'); wp_insert_term('Halloween', 'theme'); } }
2. Styling Your Custom Taxonomy Input
To add input menus to your WordPress post interface, you want to use the WordPress add_meta_box command. In the example code below, we add a new custom field called Theme into our WordPress post interface. Simply include the code into your functions.php theme or plugin file.
function add_theme_box() { add_meta_box('theme_box_ID', __('Theme'), 'your_styling_function', 'post', 'side', 'core'); } function add_theme_menus() { if ( ! is_admin() ) return; add_action('admin_menu', 'add_theme_box'); } add_theme_menus();
The add_meta_box function adds your_styling_function to the WordPress blog system so that it gets called whenever the Edit Post screen is rendered. You can use the same function to add input code to Edit Page and Edit Link screens.
The example your_styling_function below will add a drop-down menu to your blog Edit Post screen, containing all the current terms on your theme custom taxonomy.
// This function gets called in edit-form-advanced.php function your_styling_function($post) { echo '<input type="hidden" name="taxonomy_noncename" id="taxonomy_noncename" value="' . wp_create_nonce( 'taxonomy_theme' ) . '" />'; // Get all theme taxonomy terms $themes = get_terms('theme', 'hide_empty=0'); ?> <select name='post_theme' id='post_theme'> <!-- Display themes as options --> <?php $names = wp_get_object_terms($post->ID, 'theme'); ?> <option class='theme-option' value='' <?php if (!count($names)) echo "selected";?>>None</option> <?php foreach ($themes as $theme) { if (!is_wp_error($names) && !empty($names) && !strcmp($theme->slug, $names[0]->slug)) echo "<option class='theme-option' value='" . $theme->slug . "' selected>" . $theme->name . "</option>\n"; else echo "<option class='theme-option' value='" . $theme->slug . "'>" . $theme->name . "</option>\n"; } ?> </select> <?php }
Lines 4-5 – Add security nonce check.
Line 9 – We use the hide_empty=0 argument for the get_terms function so that all theme choices will be returned, even the ones that have not yet been assigned to any post.
Line 15 – We use the wp_get_object_terms function to get the theme currently associated with our post so that we may pre-select it in our drop-down menu.
Lines 17-25 – Render our drop-down menu, populating it with our theme names.
Note – On lines 22 and 24, we are now setting the theme-option value to $theme->slug. As pointed out by Adam in the comments section, the taxonomy object slug is unique (unlike its name), and this will prevent duplicate taxonomy terms from being created.
Note that when you add your new drop-down menu box, the old tag input box will still appear. To only include one input box, use the remove_meta_box command as suggested by Leo Mysor in the comments section below.
remove_meta_box('tagsdiv-theme','post','core');
Note – For non-hierarchical taxonomies (like tags) you want to use tagsdiv-{$taxonomy_name}, e.g. tagsdiv-theme. For hierarchical taxonomies (like categories) you want to use {$taxonomy_name}div, e.g. themediv.
You can add the remove_meta_box command before your add_meta_box statement.
Alternatively, you can register your custom taxonomy attribute to something other than ‘post’. In the code example below, we register our theme custom taxonomy to shiba_post, which gets rid of the standard tag input box in the Edit Post screen.
register_taxonomy( 'theme', 'shiba_post', array( 'hierarchical' => false, 'label' => __('Theme'), 'query_var' => 'theme', 'rewrite' => array( 'slug' => 'theme' ) ) );
However, as pointed out by Leo, this also removes your taxonomy tab from the Posts menu and makes it difficult for others to add new items to your taxonomy.
3. Saving Your New Inputs
Now, we can insert any input panel we want for our custom taxonomy, however, we still need a way to save those input values. This can be achieved with the save_post WordPress hook. This hook allows you to execute a function of your choice when a WordPress post gets saved. There are similar hooks for saving pages and links.
Just add the save_post hook to your existing add_theme_menus function. For example, the code below registers the save_taxonomy_data function with the WordPress blog system so that it gets executed whenever a WordPress post is saved or updated.
function add_theme_menus() { if ( ! is_admin() ) return; add_action('admin_menu', 'add_theme_box'); /* Use the save_post action to save new post data */ add_action('save_post', 'save_taxonomy_data'); }
Now, you just need to specify your save_taxonomy_data function. We can adapt our own save function from the add_meta_data example on WordPress.org.
function save_taxonomy_data($post_id) { // verify this came from our screen and with proper authorization. if ( !wp_verify_nonce( $_POST['taxonomy_noncename'], 'taxonomy_theme' )) { return $post_id; } // verify if this is an auto save routine. If it is our form has not been submitted, so we dont want to do anything if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) return $post_id; // Check permissions if ( 'page' == $_POST['post_type'] ) { if ( !current_user_can( 'edit_page', $post_id ) ) return $post_id; } else { if ( !current_user_can( 'edit_post', $post_id ) ) return $post_id; } // OK, we're authenticated: we need to find and save the data $post = get_post($post_id); if (($post->post_type == 'post') || ($post->post_type == 'page')) { // OR $post->post_type != 'revision' $theme = $_POST['post_theme']; wp_set_object_terms( $post_id, $theme, 'theme' ); } return $theme; }
Lines 4-6 – First we do a nonce check to ensure that the function is being called by our very own your_styling_function. Make sure that the taxonomy_noncename and taxonomy_theme terms match those that were created earlier, on lines 4-5 in your_styling_function.
Lines 9-10 – Take no action for auto-saves.
Lines 14-20 – Check that the current user has proper permissions to edit posts.
Lines 23-28 – Associates our post with the new theme taxonomy data. It is important to do a post_type check here, because this function will also get called on post revision objects.
As pointed out by Angelia, this results in double counting the newly added taxonomy relationship.
4. Getting a Taxonomy Term Count
If you want to get the count of a particular taxonomy term, i.e., the number of objects that it is associated with, you can easily extract that figure from the WordPress term_taxonomy database.
Just add the count code into the foreach $themes loop.
global $wpdb; foreach ($themes as $theme) { $count = $wpdb->get_var( $wpdb->prepare( "SELECT count FROM $wpdb->term_taxonomy WHERE term_taxonomy_id = %d", $theme->term_taxonomy_id) ); /* Your code here to display the count ... */ }
While registering your custom taxonomy, you can link an update_count_callback function to it. This function will get called every time any term in your taxonomy gets a count update. This allows you to control what actually gets stored in the count column of your custom taxonomy terms.
$args = array( 'hierarchical' => false, 'update_count_callback' => 'test_taxonomy_count', 'label' => __('Theme'), 'query_var' => 'theme', 'rewrite' => array( 'slug' => 'theme' ) ) register_taxonomy( 'theme', 'post', $args); // This test count function just does the default WordPress operations function test_taxonomy_count($terms) { global $wpdb; $terms = array_map('intval', $terms); foreach ( (array) $terms as $term) { $count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $term) ); $wpdb->update( $wpdb->term_taxonomy, compact( 'count' ), array( 'term_taxonomy_id' => $term ) ); } }
5. All Done!
You can use the same code to style your custom taxonomy input panels for pages and links. Just change the post attribute to page or link when calling add_meta_box and use the save_page, edit_link, and add_link hooks instead of save_post.
You can also add new fields to your WordPress blog categories using a similar system.
kathy says
so i’ve successfully implemented both this and you ‘expand the wordpress quick edit’ tutorial. compliments on such intricate and valuable tutorials. i have learned a ton from your site that i can’t find anywhere else. i’m finding that if i do both, however, then i end up w/ two actions attached the the save_post hook and this is causing problems with undefined indexes: ie. nonces from one that aren’t in the $_POST of the other. can you think of a check to only run the added function if it is run on the quick edit screen versus if it is run on the normal edit post page?
kathy says
turns out that you can test for whether the save is coming from the quick edit screen by checking if $_POST[‘action’] == ‘inline-save’. (i believe it equals ‘edit’ from the edit screen.
however, in the end, i decided it was redundant to have 2 functions attached to ‘save_post’ to do the same thing: since the taxonomy metabox and the quick edit box are handling the same data, so i combined them into 1 function. works great. i was concerned about needing to use different nonces, but WP uses the same nonce name (‘_wpnonce’) in both places, so i figured i could too. thanks again!
yzlow says
Great tutorial. If anyone is already using WPAlchemy Metaboxes, I did a small tutorial on how to use your method together with it. My tutorial can be found http://yzlow.monstrosity-studio.com/custom-taxonomy-metaboxes-with-wpalchemy-metabox/54/. Thanks!
Ted says
Hi Shibashake, thanks for the great tutorial. I’ve gotten everything to work, but am stuck on removing a meta box (input field) from the custom taxonomy “Add New Category” page and “Edit Category” page.
By default, the input fields for creating or editing a category are “Name”, “Slug”, “Parent”, and “Description”. I’m trying to remove the “Description” field but can’t figure out how.
I was even just thinking about setting that field to display: none but it doesn’t have a unique class or id. Any ideas? Thanks!
Ted says
so after a lot of trial and error, i managed to remove the description field via a jquery hack.
// this removes the admin description input field when var userSettings pagenow is edit-erw_menu_cats
function erw_hide_descrip()
{
echo "
if ( pagenow == 'edit-erw_menu_cats') { // begin conditional
$(function(){
$('div.wrap form.validate table.form-table tr.form-field:last').hide(); // removed from edit category page
$('div.col-wrap div.form-wrap div.form-field:last').hide(); // removed from add new category page
});
}; // end conditional
";
}
add_action( 'admin_head', 'erw_hide_descrip' );
The only problem is, that now I’m wanting to add an input field on the custom taxonomy “Add New Category” page and “Edit Category” page but have no idea how to do this. any clues?
Ted says
finally found it….
http://wordpress.stackexchange.com/questions/689/adding-fields-to-the-category-tag-and-custom-taxonomy-edit-screen-in-the-wordpr
hope this helps someone
eko lesmana says
can i use this at WP 3.2.1?
ShibaShake says
It should work since I use it in several of my plugins. Let me know if you run into any problems.
Anonymous says
thanks for your quick reply , shibashake.
let just say, in my database, term_id for Halloween is 13. i made a post and i choosed theme ‘Halloween’. after that, i clicked Publish button. then i checked wp_posts, the id of my post is 15. then i checked wp_term_relationships, only object_id with id 15 and term_taxonomy_id is 1. not object_id with id 15 and term_taxonomy_id is 13.
Anonymous says
finally i can do it, shibashake.
maybe i lost one step. thanks for your great tutorials.
eko lesmana says
i have another question, shibasake.
how to make dropdown to be checkbox?
and how to save the data?
help me please…
Tim says
Just wanted to say thanks! – This tutorial was invaluable for me.
Having custom taxonomies as dropdowns has been something I’ve wanted to do for ages but just didn’t know where to start!
Nick says
Thanks for the tutorial!
One question though, how do you get the value of dropdown on posts/pages?
Thanks in advance!
ShibaShake says
I am not sure what your question is. Do you mean how to get the value of the dropdown menu so it can be saved?
That is shown in Section 3 – Saving Your New Inputs. The dropdown menu value can be gotten from the $_POST array.
Anna says
I have a similar question. What code can be used to actually display the taxonomy value on the post?
Anna says
Got it:
Darren says
When you mentioned Actors and Genre I was like, ‘ah this makes sense’. Then you started going on about Dragons and Beauty and then I had no idea what was happening. Further to this you stated you can’t have drop down menus, then your dragons and Beauty are in drop downs in the screenshots in step 2. I guess I need to be a wizard to understand this stuff.
ShibaShake says
LOL!
As for custom taxonomies, drop-down menus are not included as part of WordPress native. However, you can code your own drop-down menus using the tutorial here.
Dragons and Beauty are just example taxonomy terms I used for my ‘Theme’ taxonomy. They could easily be ‘Western’, ‘Action’, or ‘Romance’ if you were creating a ‘Genre’ taxonomy.
Happy wizarding! 😀