Documentation

Dynamically populate a select field’s choices

Description

Need to dynamically populate a field’s choices? This tutorial will cover how to take a value saved to the options page and use it to override the choices for a select field. As the ‘choices’ array attribute is used for the radio, checkbox and select fields, this tutorial can be transposed onto any of these fields.

Requirements

Example 1

In this example, we will load a textarea field from the options page (textarea field is called “my_select_values”) and use the text on each line as a option for the select field’s choices. The select field in this example has a name of “color”.

function my_acf_load_field( $field )
{
	// reset choices
	$field['choices'] = array();

	// get the textarea value from options page without any formatting
	$choices = get_field('my_select_values', 'option', false);

	// explode the value so that each line is a new array piece
	$choices = explode("\n", $choices);

	// remove any unwanted white space
	$choices = array_map('trim', $choices);

	// loop through array and add to field 'choices'
	if( is_array($choices) )
	{
		foreach( $choices as $choice )
		{
			$field['choices'][ $choice ] = $choice;
		}
	}

    // Important: return the field
    return $field;
}

// v3.5.8.2 and below
add_filter('acf_load_field-color', 'my_acf_load_field');

// v4.0.0 and above
add_filter('acf/load_field/name=color', 'my_acf_load_field');

 

Example 2

In this example, we will load a repeater field from the options page (repeater field is called “my_select_values”) and use the sub fields “value” and “label” as the options for the select field’s choices. The select field in this example has a name of “color”.

function my_acf_load_field( $field )
{
	// reset choices
	$field['choices'] = array();

	// load repeater from the options page
	if(get_field('my_select_values', 'option'))
	{
		// loop through the repeater and use the sub fields "value" and "label"
		while(has_sub_field('my_select_values', 'option'))
		{
			$value = get_sub_field('value');
			$label = get_sub_field('label');

			$field['choices'][ $value ] = $label;
		}
	}

    // Important: return the field
    return $field;
}

// v3.5.8.2 and below
add_filter('acf_load_field-color', 'my_acf_load_field');

// v4.0.0 and above
add_filter('acf/load_field/name=color', 'my_acf_load_field');