Support

Account

Home Forums General Issues How do I get optgroups in the Select field? Reply To: How do I get optgroups in the Select field?

  • Hi. Sorry for getting this up. But I have found in the same situation where I need 2 levels for Select field.

    In my case, I wanted to use the interface to do that, so I have made a change in my ACF select field code to permit that. If the line in the interface starts with – (for instance -Europe ) it will assume there are optgroups, so everything that comes after that line will be for that group until next – is found.

    In my case, in the interface I write:

    -Europe
    Spain
    France
    -America
    Argentina
    Peru

    and then I get a select with optgroup where Europe and America are the group headlines and the rest are the selectable options.

    In advanced_custom_fields/core/fields/select.php LINE 68 add

    		// Other way to group is using - in the field
    		if (!$optgroup) {
    		// vars
    		$new_choices = array();		
    			// Determine if there are - to group the field
    			$group = false;
    			$choices_group = array();
    			$optgroup_key = "";
    			foreach ($field['choices'] as $k => $v) {
    				if (strpos($v, "-") !== false)
    				{
    					// Next elements are optgroup;
    					if ($group) {
    						$choices_group [$optgroup_key] = $new_choices;
    						$new_choices = array();
    						$optgroup_key = $v;
    					} else {
    						
    						// Get ungrouped value from begining of the list
    						foreach ($new_choices as $l=>$w) {
    							$choices_group[$l] = $w;
    						}
    						$new_choices= array();
    						
    						$group = true;
    						$optgroup_key = $v;
    
    					}
    				} else {
    					if(strpos($v, ' : ') !== false)
    					{
    						$choice = explode(' : ', $v);
    						$new_choices[ trim($choice[0]) ] = trim($choice[1]);
    					}
    					else
    					{
    						$new_choices[ trim($v) ] = trim($v);
    					}
    					
    				}
    			
    			}
    			if ($group) {
    				// End last group
    				$choices_group [$optgroup_key] = $new_choices;
    				$field['choices'] = $choices_group;
    				$optgroup = true;
    			}
    		}