Home > OS >  How can I limit a post's taxonomy term selection to only one per level?
How can I limit a post's taxonomy term selection to only one per level?

Time:11-22

What is possible now:

A user can select multiple terms

enter image description here


Desired behaviour:

A user can select only on term per level. (Only one term on the first level and only one term on the second level)

enter image description here


I use custom taxonomies.

CodePudding user response:

First, you can limit your user with some js that you can add only on admin area using admin_enqueue_scripts

And then some code:

    jQuery('.cat-checklist input[type="checkbox"]').on('change', function(event){
        var checked = jQuery(this).prop('checked');
        // Clear all other inputs on this level:
        jQuery(this).closest('ul').find('input[type="checkbox"]').removeAttr('checked');
        // Set the value:
    jQuery(this).prop('checked', checked)
})

Tested on the quick edit screen but you've got the idea.

From the other side, you can also modify the saved data for example using the save_post hook. You'll be able to get the list of taxonomies that are going to be saved and then limit them.

  • Related