Home Forums General Issues set selected value(s) for select fields


set selected value(s) for select fields

  • Using load_field I can set the value for a text field and other fields, but I’m having problems trying to set the value for a select2 field (single & multiple) after they’ve had an array of values already added.

    I’ve tried a whole myriad of combinations in both load_field and load_value but can’t get anything to work.

    Essentially I’m after something like this:

    First, this runs to load a list of countries & languages into the fields – this works fine:

    add_filter('acf/load_field', 'load_country_language_field', 10);
    function load_country_language_field( $field ) {
    	// languages & countries are loaded into the fields

    Then I want to run something like this code to set the default single value for a country and the default values for languages. This doesn’t work:

    add_filter('acf/load_field', 'load_default_values', 20);
    function load_default_values( $field ) {
    	// put in a single country
    	if ( $field['key'] == 'field_5eca5ca92515d' ) {
    		$field['value'] = 'France';
    		return $field;
    	// put in multiple languages
    	if ( $field['key'] == 'field_5eca5ca925318' ) {
    		$field['value'] = 'English';
    		$field['value'] = 'German';
    		$field['value'] = 'Italian';
    		return $field;

    Any help appreciated!

  • A select field stores an array and your values always need to be arrays

    $field['value'] = array('France');
    // or 
    $field['value'] = array('English', 'German', 'Italian');

    ensure that you are using the value and not the label.

  • Brilliant. Thanks.

    It’s so easy when you know how! 🙂

Viewing 3 posts - 1 through 3 (of 3 total)

The topic ‘set selected value(s) for select fields’ is closed to new replies.