Home Forums ACF PRO Dynamically populate select field AND data attributes? Reply To: Dynamically populate select field AND data attributes?

  • Hi kingofmycastle,

    Actually i am very interested in finding a solution for this and i thought i was the only one trying to do this,

    i will share with you what i have found kind of useful but not a solution yet.

    1- there is a way to add a data-attribute to the wrapper of the field using
    $field['wrapper']['data-yourDataName'] = 'yourDataValue'; But unfortunately i cant find a way to add data attributes to the choices of select field “other than your way”,

    2- To solve the problem of user changing the values in option page, i would first populate the values normally from the option page like you stated in your post, then i would grab the value which is in the current post and check if it exist in the field[‘choices’], if its not exist means the original have been changed and i will add it to the array let me show you

    //This function will load a list of currencies from option page to the post page
    function tours_load_currency( $field ) 
            $field['choices'] = array();
            //get the field
            $choices = get_field('available_currency', 'option', false);
            //seprate values by new line
            $choices = explode("\n", $choices);
            //array map the values
            $choices = array_map('trim', $choices);
            //fill the choices array with currency code and value :( .. which is really bad but no other way
            if( is_array($choices) ) 
                foreach( $choices as $choice ) 
                    list($value, $text) = explode(" : ", $choice);            
                    $field['choices'][ $value . ' : ' .  $text] = $text;            
            // get the current post select value from the database 
            $post_currency = get_post_meta(get_the_ID(),"tour_currency",true);
            // if we couldnt find the database value in the field["choices"], means that it was changed in options page
            if(!array_key_exists($post_currency, $field['choices']))
                $post_currency_exploded = explode(' : ', $post_currency); // the drop down label
                //add the database value to the field["choices"] array one more time
                $field['choices'][$post_currency] = $post_currency_exploded[1];
            // return the field
            return $field;
        add_filter('acf/load_field/name=tour_currency', 'tours_load_currency');

    again if any one knows a good way to add data-attributes for choices in a select field from server side will be really great