WordPress Custom Taxonomy Input Panels

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.

Related Articles

If you enjoyed this article, please help support our site.

Comments

  1. kenny says

    great tutorial thanks!

    I want 2 custom taxonomies, but when I copy the code and change the names I get a server error.

    Any ideas why this happens?

    Thanks!

  2. Imperative Ideas says

    This just made my day man. I was almost sure I was going to spend the next few hours figuring it out myself.

  3. Johan says

    Hello and thanks for a super tutorial!
    I’m struggling to add another dropdown list, but i cant get it to work. Do you have any suggestions on how to do it?

    Much appreciated!

  4. paulius says

    Hello, thanks for great tutorial! I have one problem: I’ve created 2 dropdowns but data saving only from one (the lower one). I have read all your comments under this tutorial and I found your answer about unique HTML names of select. My both selects have different names and ids, but problem remains. Maybe you can help me? Thanks in advance!

    • says

      Did you also expand your save function to read inputs from both dropdowns? We can also print out the $_POST array and see if the proper values are being stored.

      If not, then there may be an issue with the HTML source, so I would check there.

  5. ini says

    How do you add an additional text input after the dropdown to alternatively add a new term to the taxonomy (within the same metabox)?

    Much appreciated, thank you

  6. ecp says

    I’m trying to implement this in a plugin wherein I register the taxonomy first (for a custom post type).

    First, just to be clear, is the styling function called automatically in edit_form_advanced.php? Because otherwise I don’t know how to call it from there, from the outside.

    More importantly, on the “Add New” page, I get a Notice that says “Undefined index: taxonomy_noncename in …” Why is that? What’s to be done about it?

    Thanks a mil

  7. jcnv says

    Where does one modify Step 3’s code to apply this to a custom post type? I’m stuck and getting a bit confused by lines 23-29. Brilliant post, though. This is literally the only place I’ve been able to find such a tutorial.

    Thanks!

  8. Justin Chow says

    Great Tut. I had trouble finding good info on this, but your tutorial gave me everything I needed. Thanks!

  9. James Chester says

    Great tutorial, I am working on a custom post type and I’ve created a custom metabox drop down for AM or PM but it won’t save my value. Can someone help me? I’m in a jam with my deadline looming. I can send my code.

    Best,
    James

    • says

      If something is not saving, I usually just try to echo something out in the save_taxonomy_data function and then exit. For example –

      print_r($_POST); exit;
      

      This lets me know if I am hitting the save function, and what input values it is getting.

  10. Robbert says

    Hi,
    I got it all working in my backend (created custom taxonomy drop down, saves, updates etc), but is there any possibility to use the custom taxonomies on my front-end form?

    I use a custom made front-end form. How can i display the custom made taxonomy dropdown there and be save the data once the user sends the form? Is there any code or source i can use for this?

    thnx!

  11. John says

    Thanks for the tutorial. One question, can I allow multiple selection using:
    <select multiple ='multiple'…
    I get the expected result visually, but as expected only the last value is saved. Is there a way to extend the save_taxonomy_data function to hold multiple ie array of values.
    Thanks again,
    John

      • spo says

        Any ideas for using checkboxes?

        Have come up with:


        echo "name . "' value='" . $theme->slug . "' checked='yes'>" . $theme->name . "\n";
        else
        echo "name . "' value='" . $theme->slug . "' >" . $theme->name . "\n";

        However, will only save the first option if more then one is checked, or the checked option if only one.

          • spo says

            Thanks for the reply!

            Originally I posted with [code] and this is what I had..

            if (!is_wp_error($names) && !empty($names) && !strcmp($theme->slug, $names[0]->slug)) 
            			echo "slug . "' checked='yes'>" . $theme->name . "\n"; 
            		else
            			echo "slug . "' >" . $theme->name . "\n";
            

            So, as stated, still only saves first option or onle of the selected..

            Do I need to define an array before wp_set_object_terms() and if so, where?

          • says

            Instead of doing !strcmp($theme->slug, $names[0]->slug), you would need to check for the entire $names array with something like an in_array.

  12. 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!

  13. 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!

  14. 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!

    • 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?

      • 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.

  15. 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!

  16. Nick says

    Thanks for the tutorial!

    One question though, how do you get the value of dropdown on posts/pages?

    Thanks in advance!

    • 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

          Got it:

                  ID , 'theme' );
          
          // Loop over each item since it's an array
          foreach( $terms as $term ) {
          	// Print the name method from $term which is an OBJECT
          	print $term->name . '';
          	// Get rid of the other data stored in the object, since it's not needed
          	unset($term);
          }
          ?>
  17. 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! 😀

  18. says

    Hi ShibaShake —
    Your tutorials must be the most complete on the net. I’m just getting into taxonomies (been using custom fields), and the possibilities are mind-boggling. Now, this is an off-the-wall question, but is there a way in CODE to convert a custom field value to a taxonomy term value? I know Scribu has a plugin for this, but I need for it to happen in theme itself. I think I’m asking if a value can be assigned to a taxonomy term; that is, can I do something like make $taxonomyvalue = $customfieldvalue and then use that taxonomy value for the rest of my code?

    If not possible, or too nuts, let me know!

    • ShibaShake says

      That sounds doable, although I am not sure in what context you would need to do that.

      Do you have an existing custom field that is already populated with data? If so, I would just do a one-off conversion.

  19. Amy says

    Thanks very much for this really interesting post!
    Unfortunately, I was silly enough to register a ‘test’ taxonomy. And now can’t figure out how to remove it! Any help would be hugely appreciated.
    Thanks,
    Amy

  20. Paul says

    Hi ShibaShake,

    I have a few questions, hoping u don’t mind to help out.

    Do u still keep this post up to date ?

    I mean want to take your code and implement it on my project, but I’m afraid the what-if you don’t really plan to keep it on. I myself am not a php guru so if I copy yours and use it, I won’t be able to keep it up to date later.

    I noticed in you code above, the is_taxonomy() is already deprecated, but u still have it that way.

    and also, would u please write up a post on how to make radio check box custom taxonomy input panel ?

    Anyway, Thanks for this post, it’s very useful, a lot of people have linked to this page.

    • ShibaShake says

      Hello Paul,
      Unfortunately, it is simply not possible to go through all previous posts every time there is a WordPress release. However, if updates get pointed out to me in comments, as you have done, I will usually go back and update the post.

      In terms of radio boxes, all you need to do is use the radiobox form inputs in your_styling_function instead of the dropdown menu form inputs. Something like this –

      echo "" . $theme->name . "
      n";
  21. Manny Fleurmond says

    One thing that I can’t seem to work with your code: if the taxonomy is set to work like a category ie hierarchical, then the meta box wordpress creates automatically doesn’t get removed when you call the remove_meta_box function. Would you happen to know if there is a way around this?

  22. JR Oakes says

    I took some of this code and created a plugin that allows you to enter a Post Type and a Taxonomy on the settings screen. Then the Taxonomy Box on the post edit screen will be changes to a drop-down select field that allows you to select only one value.

    If you can add anything to make it better I am cool with that. I figured since I had to spend the time to get this working I might as well make it a plugin.

    • Griff says

      JR Oakes – absolutely love that Plugin you credted. I was wondering if there was a way to have the title of the Meta Box appear as the Title case version of the taxonomy? For example, a taxonomy for Manufacturers appears with title “manufacturers”. I had a look at the code, but couldn’t really figure it out 🙂

  23. Jacobo Polavieja says

    Hello Shibashake!

    Thanks a lot for the tutorial. This blog is full of valuable resources for WordPress.

    I’ve tried your code and have experimented a weird thing, so I hoped you could help me. If I paste your code directly into my theme’s functions.php all works well. However, if I try to include in a plugin I’m developing two things happen:
    1. The “Themes” dropwdown appears with the “None” option, and below it there are two completely blank (which is weird, as if it was three at least I could thing there’s a problem retrieveing the taxonomy names, but it is just to blank options).
    2. The “Themes” NORMAL box (in the sense of the usual tags display format) doesn’t appear (it does when I paste the code into functions.php), although I haven’t still used the tip of using “remove_meta_box(‘tagsdiv-theme’,’post’,’core’);”.

    If you could have a look it’d be of great help as you seem the only one filling this necessity of ours of having custom admin displays

    The plugin code: http://wordpress.pastebin.com/78nW5yYC
    A screenshot: http://img291.imageshack.us/img291/4453/dropdownj.jpg

    Hope you can help, because after looking at it lots of times I can’t get what I may be doing wrong.

    Thanks for all this blog, is amazing.

    • ShibaShake says

      Hmmm, the first thing I would do is clean-up the class initialization function. Don’t just paste the whole tutorial code in there because you are also doing calls to add_action-init in your plugin proper. In general, you only want to have one init function and one admin_init function so I would integrate those.

      Also, I would take the tutorial functions out of the initialization process and put them in the class.

      I am not sure if this will solve your issues but the code is difficult to debug in its current structure.

      Are you trying to add the custom taxonomy to posts? or to your new custom post type? If you are adding it to your new custom post type then you should use your custom post type name instead of ‘post’.

      Good luck!

  24. vilo says

    Great tutorial! I have one question that wasn’t mentioned. I am using p2 template that allows blog editing by multiple users from the front end (not in admin). How do I get taxonomy input form to the front so when user is submitting his post he can choose some other options from the pulldown menus of taxonomies? Even better how could this be hooked to the jquery so your form could be used from the front for article ratings, opinion selections and such. Any direction would be much appreciated.

    • ShibaShake says

      I am not familiar with the inner workings of the p2 theme. You can probably get the best help from the p2 theme creators.

      • Jacobo Polavieja says

        Hello again and thanks for taking the time to look at the code and answer.

        Following your advices I’ve cleaned up the code a litte bit. I’ve moved the taxonomies onto functions.php, as they are more likely to change than the custom types, which I’ve left on the plugin file.

        The only problem that’s left now is that I’d like to have the custom taxonomy display on both my ‘post’ types and my custom post types.

        I’ve tried to pass the add_meta_box function two parameters like this:
        add_meta_box(‘main_country_box_ID’, __(‘Main country’), ‘your_styling_function’, array( ‘post’, ‘custom_post_type’ ), ‘side’, ‘core’);
        But WordPress throws a “Illegal offset type” warning and doesn’t show the box in either type.

        Other options I’ve tried have been:
        A) Doing two calls:
        add_meta_box(‘main_country_box_ID’, __(‘Main country’), ‘your_styling_function’, ‘post’, ‘side’, ‘core’);
        add_meta_box(‘main_country_box_ID’, __(‘Main country’), ‘your_styling_function’, ‘custom_post_type’, ‘side’, ‘core’);

        —> The box is displayed JUST on the “post” type editing screen, not on my custom post type’s.

        B) Trying to get it to work just on the custom post type:
        add_meta_box(‘main_country_box_ID’, __(‘Main country’), ‘your_styling_function’, ‘custom_post_type’, ‘side’, ‘core’);

        —> The box doesn’t get displayed in either type

        All of this, of course, with the taxonomy previously registered for both types in your “create_nameoftaxonomy_taxonomy” function:
        register_taxonomy( ‘main_country’, array( “post”, “new” ), array( ‘hierarchical’ => false, ‘label’ => __(‘Main country’), ‘query_var’ => ‘main_country’, ‘rewrite’ => array( ‘slug’ => ‘main_country’ ) ) );

        All code at: http://wordpress.pastebin.com/YQtP7AMg

        I can’t find what may be conflicting. If you could provide any help it’d be great as I’m so close!

        Thanks a lot for everything, have subscribed to your blog, one of the most interesting ones in the WordPress world.

        • ShibaShake says

          Try doing –

          add_meta_box('main_country_box_ID', __('Main country'), 'your_styling_function', 'new', 'side', 'core');
          

          Put in the name of your custom post type, i.e. ‘new’ instead of ‘custom_post_type’.

          • Jacobo Polavieja says

            That worked!

            The way it is put on the Codex doesn’t really clarify that point much, or at least I didn’t get it well.

            Thanks a lot for helping me through this, very kind on your part. I now have all fully working!

            Many many thanks. Cheers!

  25. Zak says

    Hi,
    This has been really helpful for me since I am designing a site for a college newspaper which needs a lot more cms functionality and a lot less of the blog feel. I made two drop down menus within my article taxonomy for the section and the issue but it will only register one (the lower one on the screen). Is there any way to get both of them to work? I am also looking into having the issue selection be separate since I will most likely be posting all articles from the same issue at once and maybe having it at the top of the admin screen but I am guessing that I might have a similar problem. Any help would be greatly appreciated!

    • ShibaShake says

      You can add as many drop-down menus as you want. Just make sure that the HTML names associated with each of them is different (line 12), and when you save the results, make sure you are getting the values from the right drop-down menu.

      <select name='my_unique_name_here' id='my_unique_name_here'>
      
      • Zak says

        Well the problem that I am having isn’t making the boxes it is saving two separate boxes when I press the publish (or save draft) button to save the changes. With all of the other settings you normally don’t have to do them one at a time so I would think that there should be a way to do this. I tried switching the order of the buttons physically by moving the boxes and it only registers the lower down button. The part I am really having trouble with is that it doesn’t seem to be a problem with the code of a specific button since they both work separately and it is only when together that one doesn’t work. Also it didn’t seem to matter where on the page they were, only that one was above the other. Maybe I could combine them into the same box… Any thoughts?

  26. D Barnes says

    this is a beautiful tutorial. very useful. i am trying to add radio buttons though, rather than a drop-down list. i know you say: “If you are looking for a drop-down menu, or a radio button list, you are out of luck.” but on an introductory page you say, “Substitute the default tag interface with a drop-down menu, radio button list, or something else.” do you give directions on this anywhere? thank you.

    • ShibaShake says

      You can do something like this for your styling function (from lines 8-28) –

      	// Get all theme taxonomy terms
      	$themes = get_terms('theme', 'hide_empty=0'); 
       
              $names = wp_get_object_terms($post->ID, 'theme'); 
              ?>
              <input type="radio" name='post_theme' value="" < ?php if (!count($names)) echo "checked";?>> None
      < ?php foreach ($themes as $theme) { if (!is_wp_error($names) && !empty($names) && !strcmp($theme->slug, $names[0]->slug)) echo "<input type='radio' name='post_theme' value='{$theme->slug}' checked> {$theme->name}
      n"; else echo "<input type='radio' name='post_theme' value='{$theme->slug}'> {$theme->name}
      n"; }

      Instead of echoing the HTML for a drop down list just echo the HTML for radio buttons.

  27. Nuwanda says

    Thanks for this, Shiba. It answered a lot of questions.

    I’m designing a small real estate site and decided to used custom taxonomies for the property listing data: price, bedrooms, etc. Of course the standard taxonomy checkbox interface was useless as I need a variety of inputs. This article was a big help.

    But since I need a lot of meat boxes for my data inputs, I guess the best solution is to set up a master array containing the parameters for each meta box and then loop through a constructor function?

    Else I end up with a very long script.

    • ShibaShake says

      But since I need a lot of meat boxes for my data inputs, I guess the best solution is to set up a master array containing the parameters for each meta box and then loop through a constructor function?

      Yeah that makes a lot of sense. It is what I normally do in my plugins.

  28. says

    in part 2, your code on line #22, I had to change theme->name to theme->slug for use with a hierarchical taxonomy. Otherwise it kept creating new terms.

  29. says

    How would you add numbers to a drop down box so that they are sorted correctly and not as strings? eg 1,2,10,11,20 rather than 1,10,11,2,20

    • ShibaShake says

      One way to do this would be to create an array of taxonomy_id -> count, and then just run PHP asort on the array. Then you can loop through the elements in the sorted array to display them in your drop down box.

  30. Angelia says

    Me again. Okay, so, I thought I was in the clear with that solution, but, alas, no bueno again. Turns out that using the code for the custom dropdowns is doing something wonky with the post counts in the taxonomy. When I clear out all taxonomy terms etc., fire up this code in functions file and go to admin, all looks good, 0 posts for term, but, when I add a term to a post, save and then go to the taxonomy menu, it says that there are 2 posts under that term when there is only one. When I then delete the term, it says there is 1, when there is now 0. If I remove the custom styling/saving from functions file and repeat process using default meta box, the count is correct, 0,1,0. Any clues on this one?

    • ShibaShake says

      Thanks for uncovering this bug.

      The reason why count is incremented twice is because a taxonomy relationship gets saved for the post and another gets saved for the post revision.

      To fix this count problem, do a post_type check in your save_taxonomy_data function, e.g.

      	$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' );
       	}
      

      I will update the article tomorrow. Now I am off to bed.

  31. Angelia says

    I’m really struggling to figure out where to add in the show_option_none in this code so that there is an option to remove the taxonomy from a post if assigned in error. I see that it is available in the image example of your code, so, perhaps you could enlighten us?? Would be greatly appreciated. I believe your example here is the only one on the internet at present discussing how to customize the administrative inputs for custom taxonomies, so, thank you very much for that. I would love to see this elaborated on even more by those in the know. I’ve been wrecking my brain trying to work out how to provide multiple input options on a site I’m currently developing. I know things are about to change considerably in WP3.0, so, I want to be sure that the methods that I am using initially will be easily converted to take advantage of the new core functions once they are implemented.

    • ShibaShake says

      Hello Angelia,
      One way to do it is to add an additional “None” option to the drop down menu, [I have added it to the article above] e.g.

      ?>
      <option class='theme-option' value='' 
      < ?php if (!count($names)) echo "selected";?>>None
      < ?php
      

      This will set the theme taxonomy value to NULL later on in the save_taxonomy_data function - i.e., it will remove the taxonomy term from the post.

      Let me know if you run into more problems.

    • Angelia says

      Thanks so much for the help Shibashake! I’ve just about been driving myself batty with all of this 😉 I have a client site that I’m building currently, and the main thing that they provide is lesson plans for teachers. My goal is to construct a backend admin that makes it easy for teachers to create the plans in the post editor ( taxonomy non-hierarchical modules ( dropdown ) for grade level, subject etc., custom taxonomy heirarchical for a gigantic ( dropdown ) listing of applicable state standards ), custom taxonomy default selection for general things like materials and the default post tags for other searchable descriptions … you get the point. Of course, then I have to have all of those same modules provide for in-depth searchability of the plans for the front end user. The new taxonomy, custom post types, and admin hooks are absolutely perfect for implementing all of this, but, my goodness, not only is there very little info out there at the moment, I’ve been watching the trac to see how things are coming along, and just about everything that I need to custom code to make this happen, is going to be implemented in 3.0. I’m pulling my hair out to work out how I should implement this stuff now, without having to redo everything in a month from now. I’ve scoured the available plugins ( simple taxonomies, custom taxonomies and gdtaxonomy tools ) in an attempt to put something custom together for my client to be able to use now, but, they all fall short in one way or another. Custom Taxonomies creates its own table, and I experienced some duplicate counts with it, not to mention there is a bug with not being able to deselect a selected term in the custom checkbox metabox. Simple taxonomies is really really simple, providing a nice start, but, doesn’t take into account hierarchical, or custom post type. I tried implementing them in there myself, but, no bueno. GD tools is mostly fluff, and the one feature that I was interested ( deletion ) doesn’t work. I checked the database twice, and the terms were still there. I’ve never written my own plugin from scratch, I mostly just do customizations of existing code ( self-taught … what can I say ), so I’m not really confident yet in my ability to put a beast like that together properly myself, especially after looking through the trac at all of the customizations that are having to be made on so many levels of core files just to implement these big changes.
      It seems that in the trac, they are extending Walker to deal with dropdowns for hierarchical terms.
      I’m rambling. My conclusion is to 1. remove any plugin attempts ( my custom ones or otherwise ) for now, 2. stick to the basics ( with your style inclusions ) 3. keep it all in the functions file and 4. hold off on implementing the hierarchical taxonomies until the 3.0 release. Then I’ll just hold my breath that along with the 3.0 release comes a taxonomy column in edit.php, singular and plural terms, easy styling of meta boxes, and the ability to transition what I’m doing in my functions file, to the core without screwing anything up in the database, ie unregister_taxonomy. Ha! Wish me luck. Should be fun explaining all of this to my client … always is.

  32. says

    Hello, I got error with your_styling_function
    Says “Warning: strcmp() expects parameter 2 to be string”.

    I just copy and paste your code, nothing modified. ❓

    • ShibaShake says

      Thanks for pointing that out Leo. The strcmp command should actually read –

      !strcmp($theme->name, $names[0]->name)
      

      There should be a ‘->name’ after $names[0]. Please let me know if you run into any more problems.

      • says

        Thank you for quick reply. It works!

        I think it’s better to use remove_meta_box to remove the original input taxonomy box, rather than register it to “shiba_post”. In this way the “Theme” tab will still appear in the admin menu, as a submenu under “Posts”, this lets other webmasters easily add more taxonomies.

        Thanks again.

  33. ShibaShake says

    Hello Giraldi,

    Haven’t done anything like that myself … the best way to go would depend somewhat on the complexity of your hierarchy. If it is free-form like WP categories then it is probably easiest to look at the WP source and adapt the existing code to your own needs.

    The wp_dropdown_categories function is in the wp-includes/category-template.php file. I looked at it briefly, and it definitely looks adaptable.

    The function itself is not very large, and it only uses one core object – Walker_CategoryDropdown which can be found in wp-includes/classes.php.

    Instead of doing –

    $categories = get_categories( $r );

    Get you own list of taxonomy objects instead. Then you will also need to play around with the Walker_CategoryDropdown object in terms of what attributes you want to display.

  34. says

    Tx for the great tute, ShibaShake! Been looking for this.

    Just wondering, though.. Do you know how to create, with custom taxonomies, something similar to wp_dropdown_categories, that is, I need to have it show the post count and also be in a dropdown menu in the home page?

    Tx agian for the tute! Cheers!

  35. ShibaShake says

    Hi MacBoy,

    Glad you enjoyed the tutorial 🙂

    I am actually not affiliated with Justin. I do enjoy his articles, so I link to them when I write about related topics.

  36. MacBoy says

    Hey there ShibaShake,

    This is an excellent tutorial. I’m glad that I’ve found a teammate of Justin Tadlock’s!

    😉

    You have a terrific talent in explaining things, keep it up!

    🙂

  37. ShibaShake says

    Oh btw – also look into using child themes so that you can easily keep all your changes across theme updates.

    • ShibaShake says

      Ok – it is because you did not yet define a “your_styling_function”.

      Just paste the your_styling_function example I gave above (the 3rd code snippet) into your functions.php file and the warning should go away.

  38. ShibaShake says

    To restyle the custom taxonomy input interface, you must use the add_meta_box command. – use it where?

    It goes in the functions.php file – best in a child theme area.

    the register_taxonomy line goes into your functions.php file as well. I just pasted that exact line in my functions.php, and it seemed to work fine, so I am not sure where your error is coming from.

    Could you post some of your surrounding code? Might help in seeing what the issue is.

  39. says

    This tutorial answered a lot of questions in using WP Custom Taxonomies – as the codex is very shy on documentation and examples.

    Problem I couldn’t use it.
    From the beginning: To restyle the custom taxonomy input interface, you must use the add_meta_box command. – use it where?

    Further on I get a Parse error: syntax error, unexpected ‘=’, expecting ‘)’ error, somewhere it seems because of this line

    register_taxonomy( 'theme', 'post', array( 'hierarchical' => false, 'label' => __('Theme'), 'query_var' => 'theme', 'rewrite' => array( 'slug' => 'theme' ) ) );

Leave a Reply

Your email address will not be published.