Support

Account

Home Forums General Issues How to Narrow Categories Displayed in ACF? Reply To: How to Narrow Categories Displayed in ACF?

  • No problem! In that case, try this.

    
    function acf_load_field_choices( $field ) {
    
      	// Create an empty array
    	$field['choices'] = array();
    
      	// Get parent categories and order by name
    	$categories = get_categories( 
    		array(
    			'orderby' => 'name',
    			'hide_empty' => 0,
    		) 
    	);
    
      	// Create a counter variable for the array
    	$i = 0;
    
    	foreach( $categories as $category ) {
    
    		// Get the top level categories
    		if ( $category->parent == 0 ) {
    
    			$field['choices'][$i] = $category->name;
    
    			$i++;
    
    			// Get subcategories within the parent category only
    			foreach ( $categories as $subcategory ) {
    
    				if ($subcategory->parent == $category->term_id) {
    
    					$field['choices'][$i] = $subcategory->name;
    					$i++;
    				}
    			}
    
    			$i++;
    
    		}
    	}
    
      	// Return the result
    	return $field;
    
    }
    
    add_filter('acf/load_field/name=test', 'acf_load_field_choices');