Home Forums General Issues Pre-selecting choices in a select2 field in the front-end. Reply To: Pre-selecting choices in a select2 field in the front-end.

  • Thank you for the prompt reply, John. Much appreciated.

    I am indeed using a Select2 implementation in the front-end, as opposed to the ACF form. This is because I can’t seem to customise the ACF form in the way that I’d like to – for this particular project, at least. But I’ve used the ACF form many times before.

    Since your response though I’ve managed to figure out a PHP-only solution using get_field_object. It’s a little rogue perhaps, but it seems to have done the trick.

    Here’s my solution:

    <select id="user_professional_interest" name="user_professional_interest[]" multiple="multiple" style="width: 100%">
    <option value="business" <?php $interests = get_field_object('user_professional_interest', 'user_'.$MyUser->ID); if( $interests && in_array('business', $interests) ) { ?>selected="selected" <?php } ?>>Business, consulting and management</option>
    <option value="charity" <?php $interests = get_field_object('user_professional_interest', 'user_'.$MyUser->ID); if( $interests && in_array('charity', $interests) ) { ?>selected="selected" <?php } ?>>Charity and voluntary work</option>

    As I don’t need to dynamically change the options in the select field, I can hardcode them into the template. Using get_field_object, I retrieve the selected choices from the ACF field in the back-end (in this case, attached to a User). Then, for each option in the list, I check whether or not its value is included in the array. If it’s included, I add selected="selected" to the option.