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 🙂
Posted in Code, WordPress Plugins
About Websavers
Websavers provides web services like Canadian WordPress Hosting and VPS Hosting to customers all over the globe, from hometown Halifax, CA to Auckland, NZ.
If this article helped you, our web services surely will as well! We might just be the perfect fit for you.
Thanks You Its Really Worked
Hey Muhammad, you’re welcome!
I am using astra theme can you advise as to where i put the js. Is it in the header body or footer Thanks
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.
Put it in a Custom Layout Hook.
https://wpastra.com/docs/custom-layout-hooks/