Search code examples
wordpresstaxonomy

Creating pre-defined taxonomies in WordPress


I’m creating a WordPress plugin, that in turn creates a custom post type for MMA fighters. I want to organise fighters by weight class, so though this would be a good use of a custom taxonomy.

I’ve created a weight class taxonomy like this:

<?php
register_taxonomy('mma_weight_class', 'mma_fighter', array(
    'hierarchical' => false,
    'label' => __('Weight Class'),
    'query_var' => true,
    'rewrite' => true
));

However, this doesn’t seem to yield quite what I want. When I go to add/edit a fighter post, there’s a weight class panel that displays like the following:

enter image description here

What I’d like instead is a weight class panel like that, but with options (i.e. Lightweight, Middleweight, Heavyweight etc) predefined by my plugin and displayed as a drop-down list, rather than an open input as above where the user can add any ol’ option.

Is it possible to create pre-defined options for a taxonomy like this?

Update

So, I found the wp_insert_term() function, programmatically added the weight classes, and changed hierarchical to true in the taxonomy definition. This gets me closer to what I want, as I now have this:

enter image description here

However, I’d rather they were radios instead of checkboxes (so users could only select one weight class), and that the “+ Add New Category” option wasn’t available, as I only want users to choose from the pre-defined options and not be able to create their own.


Solution

  • The metabox is looking like this because you defined the 'hierarchical' => false argument, if you set that to 'hierarchical' => true it'll adopt the categories style metabox, with checkboxes but i think you don't wanna give the oportunity to the users to create sub-categories, because that would be wrong.

    You could have 3 approaches here:

    1) Set 'hierarchical' => true but this will enable a fighter be on more than one class

    2) Change the default metabox for this custom post type, replacing the checkboxes for radio buttons

    3) Create a custom metabox, with radio buttons too

    Sorry for bad english