Support

Account

Forum Replies Created

  • 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);
  • For any Googlers still arriving in this thread, the above fix is no longer applicable.

    I disabled ACF 4 before doing the database upgrade for v5 Pro and found my field groups had disappeared.

    The ‘Upgrade Database’ prompt checks an option named ‘acf_version’ in wp_options, so I reverted that to my 4.x version, enabled both the 4.x and 5.x plugins as per the upgrade documentation, and the Upgrade Database prompt reappeared and ran successfully.

Viewing 2 posts - 1 through 2 (of 2 total)