Home Forums Backend Issues (wp-admin) Select Parent Tax Term Then Child? Reply To: Select Parent Tax Term Then Child?

  • It’s been a little while, but I wanted to build onto what ChrisAtMogul started here because this worked wonders for me, but I had to do some tweaking to get it to work the way I needed it.

    Chris’s code is good for working with one multiselect field, because it allows you to whittle your results in the same field down. However, what I wanted to do was to select a parent taxonomy term in a select, and then have another ACF field directly after that only listed the child terms. That way, they could be pulled from ACF as distinct entities if need be.

    So, this requires two fields, both assigned the Taxonomy type. And please note that this is only a singluar level parent/child relationship. Any further, and you’d need to add more to the JS and to the PHP to make this cascade into grandchildren, etc.


    	$(document).ready( function() {
    		acf.add_filter('select2_ajax_data', function( data, args, $input, field, instance ){
    			var parent_field_key = 'field_5f4fcb8f3a1a2'; // Parent Field
    			var target_field_key = 'field_5f4fd4201446c'; // Child Field
    			if( data.field_key == target_field_key ){
    				var field_selector = 'select[name="acf[' + parent_field_key + ']"]'; //the select field holding the values already chosen
    				if( $(field_selector).val() != '' && $(field_selector).val() != null ){
    					parent_id = $(field_selector).val();
    				} else{
    					parent_id = 0; //nothing chosen yet, offer only top-level terms
    				data.parent = parent_id;
    		  	return data;

    Functions file

    function custom_acf_taxonomy_hierarchy( $args, $field, $post_id ){
    	$parent_id = false;
    	if ( $field['key'] == 'field_5f4fcb8f3a1a2' ) { // Parent
    		$parent_id = 0;
    	} else if ( $field['key'] == 'field_5f4fd4201446c' && !empty( $_POST['parent'] ) ) { // Child
        	$parent_id = (int)$_POST['parent'];
        if ( $parent_id !== false ) {
        	$args['parent'] = $parent_id;
        return $args;
    add_filter('acf/fields/taxonomy/query/key=field_5f4fcb8f3a1a2', 'custom_acf_taxonomy_hierarchy',10,3); // Parent
    add_filter('acf/fields/taxonomy/query/key=field_5f4fd4201446c', 'custom_acf_taxonomy_hierarchy',10,3); // Child

    I hope this manages to help someone like ChrisAtMogul’s code helped me. Thanks again!