Home › Forums › Backend Issues (wp-admin) › Select Parent Tax Term Then Child? › Reply To: Select Parent Tax Term Then Child?
Since this topic still rates highly in Google results, just thought I would chime in with a really simple way to do this using the Javascript API.
The ACF Javascript API has a filter ‘select2_ajax_data’ which allows us to send extra data with the AJAX request which gets the list of terms for us to choose from.
We can use this along with the PHP filter ‘acf/fields/taxonomy/query’ to do our dynamic filtering.
The idea is simple enough. Each time we click the ACF taxonomy multiselect field to make a selection:
– If we have not selected any terms yet, we want to see top-level terms (parent = 0)
– If we have selected one or more terms already, we only want to see children of the most recent term selected.
The most fragile bit of this is the jQuery which finds the most recent term selected – you may have to tweak this in future.
The code:
/* Javascript / jQuery */
acf.add_filter('select2_ajax_data', function( data, args, $input, field, instance ){
var target_field_key = 'field_5c7634ca3413f'; //YOUR TARGET FIELD KEY HERE
if(data.field_key == target_field_key){
var field_selector = '[name="acf[' + target_field_key + '][]"]'; //the select field holding the values already chosen
if($(field_selector).val() != '' && $(field_selector).val() != null){
var collections = $(field_selector).val();
parent_id = collections.pop(); //parent of available options will be set to the last term selected
}
else{
parent_id = 0; //nothing chosen yet, offer only top-level terms
}
data.parent = parent_id;
}
return data;
});
/* PHP */
function custom_acf_taxonomy_hierarchy( $args, $field, $post_id ){
$args['parent'] = empty($_POST['parent']) ? 0 : $_POST['parent'];
return $args;
}
add_filter('acf/fields/taxonomy/query/key=field_5c7634ca3413f', 'custom_acf_taxonomy_hierarchy',10,3);
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.