Support

Account

Home Forums General Issues Populate select field with meta values not working.

Solved

Populate select field with meta values not working.

  • I can’t seem to be able to pre-populate a select field based on certain custom fields in a post_type.

    Here’s the code:

    function acf_clientcenter_select( $field) {
    	
    $field['choices'] = array();
    
            $offices = get_posts('post_type=offices&posts_per_page=-1');
    
            foreach($offices as $office){
    			
    			$text = get_field( "msq_officename", $office->ID );
    			$value = get_field( "msq_officeslug", $office->ID );
    			
                $field['choices'][ $value ] = $text;
            }
    
    wp_reset_postdata();
    
    return $field;
    
    }  // end populate ACF select with client center values
    add_filter('acf/load_field/key=field_52924aca4d5c8', 'acf_clientcenter_select');

    Here are the array items in $field:
    Array
    (
    [choices] => Array
    (
    [14thstreetcorridor] => 14th Street Corridor
    [georgetown] => Georgetown
    )

    )

    This is the front-end html result:
    <select id="acf-field-team_client_center" class="select" name="fields[field_52924aca4d5c8]" ><option value="null">- Select -</option></select>

    Any assistance is greatly appreciated.

  • Hi @nufantech

    Thanks for the above code. Your debugging of $field shows that the choices are being correctly populated. Where in the code do you place the debug code?

    P.S. the wp_reset_postdata function is not needed as you have not setup any post data

    Thanks
    E

  • The above code is in functions.php. To debug, I’ve removed the above code from the function in functions.php and placed into a post template, removing return $field and replacing with print_r($field).

    Doing this, I can see that the array is formatted as follows:

    Array
    (
    [choices] => Array
    (
    [14thstreetcorridor] => 14th Street Corridor
    [georgetown] => Georgetown
    )
    
    )

    The values just aren’t making it to the select field, which is located on a custom post type add/create screen via the WP Dashboard.

    I’ve tried using both the name and key filter, neither of which is working for me.

  • Hi @nufantech

    Can you please debug the code within the filter?

    You are expecting the filter to run, but perhaps it is not.
    Before the last line:
    return $field;

    Can you please use this:

    
    echo '<pre>';
    	print_r($field);
    echo '</pre>';
    

    Thanks
    E

  • I get this:

    Array
    (
    [choices] => Array
    (
    [14thstreetcorridor] => 14th Street Corridor
    [georgetown] => Georgetown
    )

    )

  • This is solved. I needed to move the code closer to the top of functions.php. Filter was firing too late.

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

The topic ‘Populate select field with meta values not working.’ is closed to new replies.