1

Is it possible to create a custom taxonomy so that only a single term can be selected for a particular post? Meaning that in post editing admin page there should be radio buttons or a dropdown (or whatever for single item selection) to select a taxonomy term

There is this discussion: https://core.trac.wordpress.org/ticket/14877, but seems not solved yet

3
  • Have a look on this article sitepoint.com/custom-wordpress-taxonomies although there is no indication in how to specific do what you want but there enough material for you to work out the solution that you are looking for Commented Aug 7, 2017 at 9:47
  • See wordpress.stackexchange.com/a/14309/73239 and the comments.
    – ClemC
    Commented Aug 7, 2017 at 11:30
  • the basic way GUI side is to write your own walker that generates the html for the metabox in whatever format you want. this might be tricky or not depending on what other features you want. You might also want to make sure some other process (bulk edit?) do not do it, and if this is essential and not only UI, you will need to check for it hen posts are saved Commented Aug 7, 2017 at 12:35

1 Answer 1

2

The default behaviour of WordPress doesn't allow this.

So, to do this, I'd suggest the following method:

  1. Register the taxonomy as usual
  2. Remove the taxonomy meta box so users don't select the taxonomy term the old way
  3. Create your own meta box with your own UI to replace the taxonomy meta box. So users can only select a term from your radio list or select dropdown.

The 2nd step can be done with this code:

add_action( 'add_meta_boxes', function() {
    remove_meta_box( $id, $post_type, $contex'side' );
} );

$id is the ID of the taxonomy meta box, which can be either 'tagsdiv-{$tax-name}' if the taxonomy is not hierarchical (like tags), or '{$tax-name}div' if the taxonomy is hierarchical (like category).

The 3rd step can be done manually, but as it involves with outputting fields, handling sanitization, saving data, I'd suggest using a library like Meta Box plugin to do that. (Disclaimer: I'm the author of the plugin).

The code to do for meta box looks like this:

add_filter( 'rwmb_meta_boxes', function( $meta_boxes ) {
    $meta_boxes[] = array(
        'id' => 'custom-meta-box',
        'name' => 'Taxonomy Name',
        'context' => 'side',
        'fields' => array(
            array(
                'id' => 'custom_taxonomy',
                'name' => 'Taxonomy Name',
                'taxonomy' => $taxonomy_slug,
                'type' => 'taxonomy',
            ),
        ),
    );
    return $meta_boxes;
} );

More docs can be found here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.