How to use placeholder with Select2 and WordPress with wp_dropdown_categories

Recently while working on a site I had an issue with getting a placeholder to show up while using WordPress built in wp_dropdown_categories and Select2. The fix was pretty easy with a little bit of jQuery, which you can see below:

The problem was the method WordPress uses to set the placeholder, the text you specify for the show_option_none argument. WordPress adds this as this as the first option in the select list, but Select2 requires the first option to be blank (yes I tried just using a space in show_option_none but that did not work.

How to add placeholder with wp_dropdown_categories

So using this example below as the arguments for  wp_dropdown_categories :

And this example as our jQuery for Select2:

To explain how i’m handling this, on line 2 you will see where we are prepending a blank option to the specialty  and then executing select2 on the dropdown.  Because jQuery is NOT asynchronous (Ajax however is), that means our empty option will be added before select2 is initialized.

Profit!

Myles

Orlando, FL

Did this post help you?

Give back and rate it for me!

Related Posts