Devlog

Single selected taxonomy in WordPress

The category taxonomy is by default a multiselect widget that uses checkboxes. There are some ways to only allow one selection, like implementing your own Walker_Category_Checklist.

But the most simple solution is just replace the checkbox inputs with radio input boxes with some Javascript. In the example below, I have a taxonomy “level” that I want to make single select. Make sure you replace “level” with the name of your category.

add_action('admin_footer', 'checktoradio');

function checktoradio() {

?>
<script type="text/javascript">
jQuery("#levelchecklist-pop input, #levelchecklist input, .level-checklist input")
  .each(function() {
    this.type="radio";
  }
);
// Remove "Add new level" link
jQuery("#level-adder").hide();
// Also remove the tabs ("Most used")
jQuery("#level-tabs").hide();
</script>

<?php

}

Now the checkboxes are replaced with radio boxes. Of course this won’t prevent someone who is willing to hack on the client side code to still select multiple boxes. If you want a more secure may, you have to use PHP for it.

A downside is that in the Quick edit form, the radio boxes are not selected. Because I almost never use this Quick edit thing, you can remove it by setting the “show_in_quick_edit” option to false when you create this taxonomy with “register_taxonomy”.

Another way to remove the whole Quick edit option for a specific post type is to make use of the post_row_actions hook:

add_action('post_row_actions', 'yoursite_row_actions', 10, 2 );

public function yoursite_row_actions($actions, $post) {
  if ($post->post_type === 'lesson') {
    unset($actions['inline hide-if-no-js']);
  }
  return $actions;
}