In a recent project I was working on, I was asked to add a dropdown to the sidebar with all categories in the blog. The very first way that came to mind was using wp_dropdown_categories(), I mean, it’s already built in, I wouldn’t have to code a complicated logic just to generate the select tag and loop through all categories, adding them one by one, right? Sure, but the problem comes when this dropdown box has to be customized with a jQuery plugin like select2, and we are required to use a placeholder in it.

 

For those who haven’t used the select2 jQuery plugin, it’s an awesome plugin that makes our ugly select boxes look very cool. One of its many features is that we can add a placeholder text to the dropdown box – just like the one we can add to text boxes and such, and it does look like a placeholder, not just the empty option we have in our old style select boxes. Here comes the complicated part, for the select2 dropdown to have a placeholder text, the select box needs the first option tag to be empty, and our handy WordPress dropdown categories function does not have an option for this. I really thought it did, but after trying several combinations of arguments to pass to the function – show_option_all, show_option_none, option_none_value, none of those seemed to do the trick. That’s when I came across this post, where the solution given by the author was to do some Javascript DOM manipulation to add the extra empty option to the beginning of the select box.

 

Now, don’t think I dislike Javascript, but I don’t like using it unless absolutely necessary. Sometimes a website needs to have some cool features for UX and these can only be done with Javascript. For this particular task I knew there had to be some other way, and luckily WordPress was the answer itself.

 

The solution I came up with uses a filter hook, more specifically wp_dropdown_cats. Using this filter, we can modify the html that will print the select box. It does require some text manipulation, but I rather do this from PHP than by using Javascript.

 

I was working with a WordPress theme, so I placed this code inside my functions.php file.

Note I didn’t use preg_replace for the text manipulation part, the reason is performance. I get it, it’s a very simple text manipulation and there’s no considerable performance gain here, but if we can get something done faster one way than the other, I’d go for the faster way. I came upon this post where some users agreed this was the fastest way to do the job, and it makes sense, we all know regular expressions are not the fastest.

 

So there you have it, do let me know if you have questions or if you know of a better way of doing this.