Support

Account

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

Solving

Select Parent Tax Term Then Child?

  • Hi! Just wondering if its possible to set up the taxonomy select field to choose the parent taxonomy term, then have a second select for the child of that term??

    The reason I need selects is that the website doesn’t want users choosing more than one child term in the backend editor.

    But they do want the parent to be selected as well…

    Is this possible?

  • Hi @aaronrobb

    I’m afraid you can’t do it. ACF has a hook to modify the taxonomy query, but it can only access the data saved in the database, not the one changed on the editor page. This page should give you more idea about it: http://www.advancedcustomfields.com/resources/acffieldstaxonomyquery/.

    Could you please tell me what you want to do with the parent taxonomy? I believe a term object has a “parent” attribute which you can get easily.

    I hope this helps.

  • @james, i believe it’s a UX thing, something that will improve the site administration experience, rather than he actually need that hierarchy.


    @aaronrobb
    : you could try to make a custom field that is a chain selector. You only display one select by default – the parent terms – then, on every change you load children for that term.

  • @james We basically want our users who own businesses listed on our website to first have to pick a parent term, then get to see the possible child terms in the editor.
    So we could have ‘restaurants’ and ‘hotels’ as parent terms, then once one is selected, they can then see the child terms. So if they pick ‘restaurant’ first, then the second select should show its children, like ‘cafe’ or ‘pizzeria’.
    So a two-level dropdown would be best.


    @Ionut
    I’ve never heard of the chain selector before…how would i set that up? Do you have a reference for that?

  • Hi @aaronrobb

    I’m afraid ACF doesn’t have chain selector feature. But, for something like that I believe you can follow this guide: http://www.bobz.co/dynamically-populate-select-fields-choice-in-advanced-custom-fields/. Or maybe @iamntz has a better solution?

    Hope this helps!

  • I was not aware of an existence of this kind of addon, but i bet it should be fairly straightforward to build one. That guide looks good though, but instead of custom options you just get taxonomy terms 🙂

  • 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);
  • 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.

    jQuery/Javascript

    (function($){
    
    	$(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;
    
    		});
    
    	});
    
    })(jQuery);

    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!

  • Hi, THIS is the answer i was looking for, midwestdev.

    But, for some reason, im receiving all the parent values ​​and all the child values in the second field. Is there a way to show only the child values ​​of the selection made in the first field?

    Maybe i have to put the jQuery/Javascript in a separated file? I put it in the header

    Thanks

  • ‘tax_query’ => array(
    array(
    ‘taxonomy’ => ‘references-cats’,
    ‘field’ => ‘slug’,
    ‘terms’ => $slug
    )
    )

  • Hi midwestdev,

    Thaks for providing your version of the code.

    Any further, and you’d need to add more to the JS and to the PHP to make this cascade into grandchildren, etc.

    Can you provide and example of PHP and JS where the cascade has been extended up to 4 levels.

    I also noted that after updating the post the values in the select fields only show the parent value.

    However when you convert the ACF fields from SELECT back to checkboxes the correct values have been saved.

    So I think some additional JS is require on POST EDIT to re-populate the ACF taxonomy.

    Did you solve this?

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

The topic ‘Select Parent Tax Term Then Child?’ is closed to new replies.