Support

Account

Home Forums Backend Issues (wp-admin) Use Select2 instead of browser dropdown Reply To: Use Select2 instead of browser dropdown

  • I came across this same issue and while it can certainly be solved with custom javascript, I found another way that requires no extra js.

    I noticed that acf_render_field($field) for a custom field type, doesn’t initialize it into a select2 field with just 'ui' => 1 in the args.

    However acf_render_field_wrap($field) DOES automatically initialize select2 when the ui is set to true. The downside here is you have unnecessary nested field wrappers. So I kept digging and all it really boiled down to was needing a simple div with the necessary classes & data attributes. Then ACF is already looking for those and is the ui is also set to a true value… BOOM, select2 is initialized and works great!

    Here’s a stripped down code example of it working with a new custom field type:

    function render_field( $field ) {
    
    $field['type']     = 'select';
    $field['ui']       = 1;
    $field['choices']  = [
      'red'    => 'Red',
      'green'  => 'Green',
      'blue'   => 'Blue',
      'yellow' => 'Yellow',
    ];
    
    // Div with necessary classes/attributes to init Select2
    echo "<div class='acf-field acf-field-select' 
               data-name='{$field['label']}' 
               data-type='select' 
               data-key='{$field['key']}'>";
    
    acf_render_field($field);
    
    echo "</div>";
    
    }

    Hope that helps, good luck!