Sometimes you have a hierarchical taxonomy where you want users to pick exactly one top-level term, then optionally one of the term’s children, and optionally one of that term’s children, and so on down the hierarchy.
For example, imagine a taxonomy structured like this:
You want users to choose their vehicle type first, and then the manufacturer. You do not want users to be able to choose two vehicle types or multiple manufacturers.
There are of course many ways to achieve this, most of which involve some sort of complex relationship definitions or elaborate showing and hiding of options.
Here is a super easy way to do it with a plain ACF taxonomy field and a single WordPress taxonomy.
- The PHP goes straight in your functions.php or plugin.
- The JS you will need to enqueue via admin_enqueue_scripts.
- And finally you need to switch out field_5c7634ca3413f for your own field key, or re-jig the JS to use a field name instead.
In a nutshell, this code:
- Modifies the query which ACF uses to find the list of terms available in the field, to accept a ‘parent’ id. Only children of this parent are returned.
- Adds a filter to the Select2 control which ACF uses for its nice ajax multi-select taxonomy fields, so send a parent id with the ajax request for terms. The parent id is either zero (if you did not select any terms yet) or the id of the last term you selected. This means we only see top-level terms (children of zero) if we did not choose any term yet, or we see children of the last term chosen.