Skip to content

Instantly share code, notes, and snippets.

@ChrisWebbNZ
Last active May 5, 2022 17:56
Show Gist options
  • Save ChrisWebbNZ/e4df81256438692a2bf5b1b49be93349 to your computer and use it in GitHub Desktop.
Save ChrisWebbNZ/e4df81256438692a2bf5b1b49be93349 to your computer and use it in GitHub Desktop.
Hierarchical select for native Advanced Custom Fields taxonomy fields
/*
Got a hierarchical taxonomy in Wordpress? Want to make users select a top-level term first,
then one of its children, then maybe one of its children? Me too!
1. Create a native ACF taxonomy field, with multiple values allowed.
2. Add the following JS and PHP snippets to your theme / plugin - replace all instances of the field key with your own.
*/
/* 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);
/* 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;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment