Skip to content

Adding select2 to WP Forms

Select2 is a great jQuery library that allows for dynamic and live-searchable selection of elements in a long drop down menu.

This guide will show you how to easily add support for Select2 to WP Forms. Note that this refers specifically to the WP Forms plugin, and not general forms for WordPress.

Begin by adding the following to your theme’s functions.php file or use a Snippet plugin:

/**
 * Load Select2. Copy paste this into functions.php, then use this jQuery to init:
 * jQuery('select').select2();
 */
add_action('wp_enqueue_scripts', function(){
 wp_enqueue_style( 'select2_css', 'https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css' );
 wp_register_script( 'select2_js', 'https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js', array('jquery'), '4.0.3', true );
 wp_enqueue_script('select2_js');
});

As the comment indicates, you’ll need to activate select2 by using the code above. For example, after including the above resources, I then used the BeaverBuilder theme’s JavaScript editor (under Customizer > Scripts) to add the following to activate select2. You’ll need to find a similar location in your theme to place this code.

jQuery(document).ready(function(){
 jQuery('select').select2();
});

Finally, to match the default WP Forms styles, you can insert this into your CSS. If you’ve adjusted the styles for WP forms, then these may need to be tweaked as well.

/**
 * WP Forms Select2 Styles
 */
div.wpforms-container-full .wpforms-form .select2-container{
 border: 1px solid #bcbcbc;
 padding: 5px;
 position: relative;
}
div.wpforms-container-full .wpforms-form .select2-container .select2-selection__arrow{
 height: 34px;
}

That’s it! Enjoy ūüôā

Jordan has been working with computers, security, and network systems since the 90s and is a managing partner at Websavers Inc. As a founder of the company, he's been in the web tech space for over 15 years.

2 Comments

  1. steverichards on November 14, 2019 at 3:13 am

    I am using astra theme can you advise as to where i put the js. Is it in the header body or footer Thanks

    • Jordan Schelew on November 14, 2019 at 4:00 pm

      It should work in either the header or footer, but you’ll probably want it in the footer for performance optimization reasons. Don’t forget to wrap that activation code with script tags if you’re popping it in a header or footer and not a spot specifically designed to accept javascript.

Leave a Comment