Shiba

Adventures in WordPress

  • — Home —
  • Dog
  • Art
  • Contact
  • WordPress Articles
    • WP Plugins
    • WP Programming
    • WP Admin Panels
    • WP Theme Design
    • WP How-To
    • WP Theme Images
You are here: Home / WordPress Admin / Custom Taxonomy / WordPress Custom Taxonomy Input Panels

WordPress Custom Taxonomy Input Panels

Tweet

by ShibaShake 105 Comments

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.

Screen-shot of the tag input interface associated with all custom taxonomies.

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();
Screen-shot of your new drop-down custom taxonomy interface.

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.

Screen-shot of the Edit Post, which now has the old tag input box and the new drop-down menu box.

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

Add Custom Taxonomy Tags to Your WordPress Permalinks

How to include taxonomy tags into our custom post type permalinks.

Modify Custom Taxonomy Columns

How to expand our taxonomy screens by adding new columns.

Add Term or Taxonomy Meta Data

How to add metadata to custom taxonomy objects such as tags and categories. In particular we examine add_metadata, update_metadata, delete_metadata, and get_metadata.

Comments

1 2 Next »
  1. paulius says

    April 9, 2013 at 11:49 pm

    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!

    Reply
    • ShibaShake says

      April 10, 2013 at 1:33 pm

      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.

      Reply
  2. ini says

    April 4, 2013 at 6:05 pm

    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

    Reply
  3. ecp says

    April 4, 2013 at 6:00 pm

    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

    Reply
  4. jcnv says

    August 21, 2012 at 8:11 am

    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!

    Reply
    • jcnv says

      August 21, 2012 at 10:30 am

      Scratch that! figured it out. Lines 26 and 27 were the key!

      Reply
  5. Justin Chow says

    May 23, 2012 at 4:20 pm

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

    Reply
  6. James Chester says

    April 5, 2012 at 11:33 am

    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

    Reply
    • ShibaShake says

      April 10, 2012 at 11:57 am

      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.

      Reply
  7. Robbert says

    March 20, 2012 at 9:19 am

    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!

    Reply
  8. John says

    March 9, 2012 at 7:34 pm

    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

    Reply
    • ShibaShake says

      March 10, 2012 at 1:33 am

      Try –

      <select name='post_theme[]' id='post_theme' multiple>
      
      Reply
      • spo says

        April 15, 2012 at 10:39 pm

        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.

        Reply
        • ShibaShake says

          May 1, 2012 at 7:22 am

          For multiple selections the name should have square brackets.

          <input type="checkbox" name="myname[]" value="1"/>One
          
          Reply
          • spo says

            May 1, 2012 at 6:00 pm

            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?

          • ShibaShake says

            May 1, 2012 at 8:32 pm

            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.

  9. kathy says

    January 7, 2012 at 6:45 am

    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?

    Reply
    • kathy says

      January 7, 2012 at 11:38 am

      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!

      Reply
  10. yzlow says

    November 5, 2011 at 3:57 pm

    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!

    Reply
  11. Ted says

    October 25, 2011 at 9:23 am

    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!

    Reply
    • Ted says

      October 25, 2011 at 6:40 pm

      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?

      Reply
      • Ted says

        October 25, 2011 at 6:51 pm

        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

        Reply
  12. eko lesmana says

    September 27, 2011 at 6:15 pm

    can i use this at WP 3.2.1?

    Reply
    • ShibaShake says

      September 28, 2011 at 3:41 pm

      It should work since I use it in several of my plugins. Let me know if you run into any problems.

      Reply
      • Anonymous says

        September 28, 2011 at 6:18 pm

        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.

        Reply
        • Anonymous says

          September 28, 2011 at 8:26 pm

          finally i can do it, shibashake.

          maybe i lost one step. thanks for your great tutorials.

          Reply
          • eko lesmana says

            September 28, 2011 at 9:45 pm

            i have another question, shibasake.
            how to make dropdown to be checkbox?
            and how to save the data?
            help me please…

  13. Tim says

    September 5, 2011 at 4:00 am

    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!

    Reply
  14. Nick says

    July 31, 2011 at 12:31 pm

    Thanks for the tutorial!

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

    Thanks in advance!

    Reply
    • ShibaShake says

      August 3, 2011 at 1:09 pm

      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.

      Reply
      • Anna says

        August 13, 2011 at 3:26 pm

        I have a similar question. What code can be used to actually display the taxonomy value on the post?

        Reply
        • Anna says

          August 13, 2011 at 3:44 pm

          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);
          }
          ?>
          Reply
  15. Darren says

    June 23, 2011 at 12:00 am

    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.

    Reply
    • ShibaShake says

      June 23, 2011 at 9:48 am

      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! πŸ˜€

      Reply
  16. Mike Carter says

    May 15, 2011 at 11:31 am

    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!

    Reply
    • ShibaShake says

      May 17, 2011 at 5:33 pm

      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.

      Reply
  17. Amy says

    May 14, 2011 at 11:38 pm

    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

    Reply
    • ShibaShake says

      May 17, 2011 at 5:20 pm

      http://core.trac.wordpress.org/ticket/12629

      Reply
  18. Paul says

    May 2, 2011 at 12:53 am

    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.

    Reply
    • ShibaShake says

      May 2, 2011 at 10:07 am

      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";
      Reply
      • Paul says

        May 7, 2011 at 4:15 am

        Thanks a lot,ShibaShake, you are the best !

        Reply
  19. Manny Fleurmond says

    December 28, 2010 at 10:01 am

    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?

    Reply
    • ShibaShake says

      January 3, 2011 at 7:58 am

      Thanks for posting the question on WP stackexchange and thanks to Jan Fabry for his great answer.
      http://wordpress.stackexchange.com/questions/6183/how-do-you-remove-a-category-style-hierarchical-taxonomy-metabox

      Reply
  20. JR Oakes says

    December 14, 2010 at 11:04 pm

    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.

    Reply
    • ShibaShake says

      December 16, 2010 at 8:00 am

      Thanks for sharing! This is one of the things I like most about the WP community.

      Reply
    • Griff says

      June 13, 2011 at 2:01 pm

      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 πŸ™‚

      Reply
  21. Manny Fleurmond says

    December 13, 2010 at 11:32 am

    Thanks for the review! I did a mashup of this code along with the “How To Create A Better Meta Box In WordPress (Part 2)(http://www.deluxeblogtips.com/2010/05/howto-meta-box-wordpress.html) code. My mashup can be found here:
    http://pastebin.com/93eydx1k

    Basically, I modified your code and added a checkbox mode to select multiple terms like you would tags.

    Reply
  22. Jacobo Polavieja says

    October 12, 2010 at 8:10 am

    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.

    Reply
    • ShibaShake says

      October 12, 2010 at 8:57 am

      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!

      Reply
  23. vilo says

    September 4, 2010 at 1:09 am

    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.

    Reply
    • ShibaShake says

      September 4, 2010 at 3:28 pm

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

      Reply
      • Jacobo Polavieja says

        October 13, 2010 at 12:56 am

        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.

        Reply
        • ShibaShake says

          October 14, 2010 at 7:57 am

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

          Reply
          • Jacobo Polavieja says

            October 14, 2010 at 11:57 pm

            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!

  24. Zak says

    August 9, 2010 at 4:22 am

    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!

    Reply
    • ShibaShake says

      August 11, 2010 at 10:14 am

      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'>
      
      Reply
      • Zak says

        August 16, 2010 at 12:58 pm

        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?

        Reply
  25. D Barnes says

    August 4, 2010 at 8:40 am

    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.

    Reply
    • ShibaShake says

      August 4, 2010 at 10:11 am

      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.

      Reply
  26. Nuwanda says

    July 29, 2010 at 3:55 pm

    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.

    Reply
    • ShibaShake says

      July 29, 2010 at 8:15 pm

      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.

      Reply
  27. adam says

    June 22, 2010 at 2:27 pm

    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.

    Reply
    • ShibaShake says

      June 23, 2010 at 7:40 am

      Thanks for the fix Adam. I have included it in the article above.

      Reply
  28. Charlie says

    May 21, 2010 at 4:43 am

    I’ll give that a go and see how I get on

    Reply
  29. Charlie says

    May 20, 2010 at 2:16 pm

    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

    Reply
    • ShibaShake says

      May 20, 2010 at 3:07 pm

      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.

      Reply
  30. Angelia says

    February 8, 2010 at 9:55 pm

    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?

    Reply
    • ShibaShake says

      February 9, 2010 at 1:35 am

      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.

      Reply
  31. Angelia says

    February 7, 2010 at 5:52 pm

    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.

    Reply
    • ShibaShake says

      February 8, 2010 at 1:12 pm

      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.

      Reply
    • Angelia says

      February 8, 2010 at 6:02 pm

      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.

      Reply
  32. ShibaShake says

    December 15, 2009 at 7:29 pm

    Thanks Leo – that is very good advice. I have added it to the article πŸ™‚

    Reply
    • Leo Mysor says

      December 16, 2009 at 7:25 am

      Not at all. Also thank you for teaching me with the custom taxonomies. πŸ™‚

      Reply
  33. Leo Mysor says

    December 15, 2009 at 6:12 am

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

    Reply
    • ShibaShake says

      December 15, 2009 at 1:01 pm

      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.

      Reply
      • Leo Mysor says

        December 15, 2009 at 4:43 pm

        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.

        Reply
        • Leo Mysor says

          December 15, 2009 at 4:44 pm

          Sorry, I mean add more terms in that taxonomy, actually.

          Reply
  34. beautiful princess says

    December 14, 2009 at 8:43 am

    what an amazing site .Ilove it alot .
    with my hearty wishes
    bye

    Reply
    • ShibaShake says

      December 14, 2009 at 3:04 pm

      Glad you enjoyed it and thanks for dropping by πŸ™‚ Hope to see you again.

      Reply
  35. ShibaShake says

    November 8, 2009 at 8:24 pm

    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.

    Reply
    • Giraldi Maggio says

      November 10, 2009 at 8:17 am

      Thanks for the reply, ShibaShake! However, I had found the solution from this link: http://wphacks.com/how-to-display-wordpress-tags-dropdown-menu/, with some modification of course.

      Reply
  36. Giraldi Maggio says

    November 8, 2009 at 6:58 pm

    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!

    Reply
  37. ShibaShake says

    October 24, 2009 at 8:40 am

    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.

    Reply
  38. MacBoy says

    October 23, 2009 at 8:12 pm

    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!

    πŸ™‚

    Reply
  39. ShibaShake says

    October 18, 2009 at 7:42 pm

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

    Reply
  40. pax says

    October 18, 2009 at 1:59 pm

    I added the lines of code from the first 2 sub-chapters, to the default WP theme, and i got: “Warning: call_user_func(your_styling_function) [function.call-user-func]: First argument is expected to be a valid callback in /Library/WebServer/Documents/testwp5/wp-admin/includes/template.php on line 2936”

    screenshot here: http://img30.imageshack.us/img30/4889/shibaprintscreen.jpg

    Reply
    • ShibaShake says

      October 18, 2009 at 7:12 pm

      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.

      Reply
  41. ShibaShake says

    October 11, 2009 at 7:39 pm

    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.

    Reply
  42. pax says

    October 11, 2009 at 5:42 pm

    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' ) ) );
    Reply
1 2 Next »

Leave a Reply to Amy Cancel reply

Your email address will not be published.

Recent Posts

  • Screen-shot of mobile responsive Poll Daddy object, where text floats properly to the right of radio buttons.How to Make Poll Daddy Objects Mobile Responsive
  • Screen-shot of blog post with no page border (flowing design).Genesis Skins 1.5
  • Screen-shot of the media manager Create-Gallery screen, while doing a post search.Shiba Media Library 3.7
  • Screenshot of the Edit Gallery screen after we hit the Create Gallery button.How to Expand the WordPress Media Manager Interface
  • Blonde girl looking through and holding a circular picture frame.Shiba Gallery 4.3
  • Close-up of beautiful blonde holding a square picture frame.Google Authorship - Good or Bad for Search Traffic?
  • Shiba Widgets 2.0
  • Media Temple screenshot of editing my sub-domain DNS entry.Using CDN Cnames with w3tc and MultiSite
  • Shiba Skins WordPress ThemeShiba Skins WordPress Theme
  • How to add the Media Manager Menu to the Theme Preview InterfaceHow to Add the Media Manager Menu to the Theme Preview Interface

Recent Comments

  • WordPress Search Widget – How to Style It (56)
    • Nelson
      - Tanks master - Fine
    • TelFiRE
      - How do you style the "X" that shows up when you start typing?
  • Update custom inputs with the proper data using Javascript.Expand the WordPress Quick Edit Menu (58)
    • Mike G
      - This is exactly what is happening to me. It is updating the value in the database and in the column, but I have to refresh ...
    • PhoenixJP
      - Thanks for this tutorial. Does someone knows if this still work with wordpress 5.03 and 5.1.
    • Francine Carrel
      - This is a very long time away from your original comment, but did you ever work it out? I am stuck on the exact same thing ...
  • Custom meta-box with a set of radio-buttons.Add a Metabox to Your Custom Post Type Screen (27)
    • mike
      - Hi Shiba am a newbie to wordpress, I just installed a plugin with a custom post type, but has no option for discussion and ...
  • Write a Plugin for WordPress Multi-Site (45)
    • Andrew
      - Hi,action 'wpmu_new_blog' has been deprecated. Use β€˜wp_insert_site’ instead.
  • Populate our Edit Gallery menu using a gallery shortcode.How to Add the WordPress 3.5 Media Manager Interface – Part 2 (29)
    • Janine
      - Still relevant in 2019.
  • WordPress Excerpt – How to Style It (36)
    • James
      - Great post. I really need some help. I have set border lines around my excerpts on my blog page/post page. The problem is ...
  • Add Custom Taxonomy Tags to Your WordPress Permalinks (123)
    • Darshan Saroya
      - Update permalinks. Go to settings > permalink and just save it.

Copyright © 2021 · Genesis Skins by ShibaShake · Terms of Service · Privacy Policy ·