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”.

functions.php

function acf_load_color_field_choices( $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;
            
        }
        
    }
    

    // return the field
    return $field;
    
}

add_filter('acf/load_field/name=color', 'acf_load_color_field_choices');

 

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”.

functions.php

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


    // if has rows
    if( have_rows('my_select_values', 'option') ) {
        
        // while has rows
        while( have_rows('my_select_values', 'option') ) {
            
            // instantiate row
            the_row();
            
            
            // vars
            $value = get_sub_field('value');
            $label = get_sub_field('label');

            
            // append to choices
            $field['choices'][ $value ] = $label;
            
        }
        
    }


    // return the field
    return $field;
    
}

add_filter('acf/load_field/name=color', 'acf_load_color_field_choices');

We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Cookie Policy. If you continue to use this site, you consent to our use of cookies.