Lately I’ve been using Custom Meta Boxes for use with custom post types. CMB makes programmatically adding specific custom fields to your posts very simple - as simple as filling out an array. The following example adds a WYSIWYG ‘sidebar’ field to posts, pages, and events (a custom post type):
You do need to include the CMB code, though -but that’s also easy. Just change the path to the correct location.
These snippets above came from a theme’s functions.php, though CMB can also be used in plugins (as my next example). Perhaps the above would be better if it were moved into a must-use plugin - maybe that’ll be my next improvement. In any case, as awesome as the above is, it gets better: see how in the sidebar field I say 'type' => 'wysiwyg'? There are plenty of field types to choose from, but you can also very easily create your own.
Getting to the point: creating a taxonomy field using Chosen
I came across Helen Hou-Sandí’s Using Chosen for a replacement taxonomy metabox & decided to see if I could get it to work with CMB. First, run through this tutorial for adding custom field types to CMB. You’ll see the last example is actually a taxonomy list - so between these two, most of my work was already done for me.
Below I’ve created an example plugin to add categories to posts using Chosen. The first few lines of the KD_Example_Class are setting that up - you could easily switch $taxonomy = 'category'; to $taxonomy = 'post_tag'; if you wanted to do this for tags, or switch $post_type to your CPT[1].
The first thing to do is create the render function. We’ll call our field type 'chosen_taxonomy'. We want to be taxonomy-independent, so we’re going to pass 'taxonomy' into the render function via $fields. We’ll initialize Chosen & build our dropdown, Chosen will do the rest automatically (see more detail about this step in Helen’s post).
Next we need to make sure this new field is saved along with the post, so we’ll do that it in the validation function. wp_set_object_terms attaches the terms in our defined taxonomy to the post ID, meaning we can use this on any post type & taxonomy.
The only issue I encountered was that I want to warn about is that for initial testing of my example plugin, I still had the original plugin I wrote all this for active - which conflicted because there were two functions for rendering & saving 'chosen_taxonomy' - so if you want to use this for multiple taxonomies & post types, you’ll need to either edit the functions, or rename them to be more specific (like, 'chosen_post_category' or something).
So far I haven’t discussed the includes() function. That one is setting up the chosen.js to only be used on the edit or add screen, and only when the post type matches.
[1] One thing you can’t do, is switch $taxonomy to an array… not even if you foreach over $field[‘taxonomy’]… you end up creating categories for all your selected tags, and tags for all your selected categories. Oops: