Support

Account

Home Forums Backend Issues (wp-admin) How can I filter the taxonomy field to show only 2nd level terms?

Solved

How can I filter the taxonomy field to show only 2nd level terms?

  • The ACF filters for the taxonomy field giving me a way to change the query args,
    and not the terms themselves.

    I want to be able to override the terms, something like this:

    $myTax = get_terms('myTax', array('hide_empty' => 0));
    
    $second_level = array_filter($myTax , function ($t) {
      return $t->parent != 0 && get_term($t->parent, 'myTax')->parent == 0;
    });
    
    return $second_level.

    How can I solved this issue?

  • You can’t override the terms shown. ACF does not have a filter for doing this and I don’t think it can be done unless you want to build a custom field type that does this. That’s a lot of work.

    My suggestion, and how I would do this would be to use a standard select field. I would dynamically generate the values for the field using your code. https://www.advancedcustomfields.com/resources/dynamically-populate-a-select-fields-choices/. If I wanted the terms assigned to the posts in WP I would create and acf/load_value and acf/update_value filters so that I could get and set the terms. https://www.advancedcustomfields.com/resources/acf-load_value/, https://www.advancedcustomfields.com/resources/acf-update_value/

  • Thanks John,it worked like a charm – I’ve created a multi-select field called “acf-user-schools” and added this:

    function acf_load_user_school_field_choices( $field ) {
    	
        // reset choices
        $field['choices'] = array();
        
    	
                   // Get all the schools hierarchy ( Country -> District -> School )
    	$schools  = getTaxonomyHierarchy( SCHOOLS_TAXONOMY );
    	
    	// Get the children (all the districits) of USA
    	$schools  = $schools [ USA ]->children;
    	
    	if ( !empty( $schools  ) AND !is_wp_error( $schools  ) ) 
    	{
    		foreach( $schools as $district ) 
    		{  
    			$field['choices'][ $district->term_id ] = $district->name;
    		}
    	}
    
        return $field;
        
    }
    add_filter('acf/load_field/name=acf-user-schools', 'acf_load_user_school_field_choices');
Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.