Skip to content

Instantly share code, notes, and snippets.

@MogulChris
Forked from ChrisWebbNZ/hierearchical-select-acf.php
Last active August 7, 2023 06:25
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save MogulChris/0e8e383d600e43190ad0dc2be4a5d6c9 to your computer and use it in GitHub Desktop.
Save MogulChris/0e8e383d600e43190ad0dc2be4a5d6c9 to your computer and use it in GitHub Desktop.
Hierarchical select for native Advanced Custom Fields taxonomy fields.
jQuery(document).ready(function($){
//Modify select2 ajax request to include a parent_id parameter, used by custom_acf_taxonomy_hierarchy()
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 parent_id = 0; //by default we want terms with parent of 0 (top level)
if($input.val() != '' && $input.val() != null){ //if we have chosen one or more terms already
var values = $input.val();
parent_id = values.pop(); //get last selected term to use as the parent for the next query
}
data.parent = parent_id;
}
return data;
});
});
<?php
//Modifies ajax requests from our select2 dropdown, $args = WP_Term_Query arguments
function custom_acf_taxonomy_hierarchy( $args, $field, $post_id ){
//default to 0 (top-level terms only) unless we get a different parent with the request
$args['parent'] = empty($_POST['parent']) ? 0 : $_POST['parent'];
//To allow multiple top-level selections, we can go back to the top of the taxonomy tree after we reach the end of a branch
/*
if(!empty($args['parent'])){
$child_terms = get_term_children($args['parent'],'YOUR_TAXONOMY_SLUG'); //change to your taxonomy slug
if(empty($child_terms) || is_wp_error($child_terms)) $args['parent'] = 0;
}
*/
return $args;
}
add_filter('acf/fields/taxonomy/query/key=field_5c7634ca3413f', 'custom_acf_taxonomy_hierarchy',10,3);
//Make the javascript available in the admin when editing a post with ACF
function custom_admin_enqueue_scripts(){
wp_enqueue_script('custom-acf-admin-js', get_stylesheet_directory_uri() . '/js/custom-acf-admin.js',['jquery']);
}
add_action('acf/input/admin_enqueue_scripts','custom_admin_enqueue_scripts');
@dizplayy
Copy link

albertvisuals

FOund some workaround/fix?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment