As much as I firmly believe in making sure that anything we build for WordPress especially as it relates to the dashboard should remain as consistent as possible.
As with anything, there are a few exceptions that I’ve made in the work specifically when it revolves around large
select elements (multiselect or no). That is, I’m a big fan of Select2 – I’ve written about it a couple of times and how I’ve used it in a couple of projects.
Because this is something that I regularly use, and because I know a number of WordPress developers (and general web developers, as well) also use this in their work – both in the dashboard functionality and in the public-facing functionality, as well – I wanted to share one way in which I’ve needed to programmatically set an option.
Set Select2 Selected Value On The Client-Side
To be clear, this post is no one that’s meant to spark a debate among jQuery (or anything other client-side library) when it comes to interacting with the DOM. For me, it’s as simple as this: WordPress ships with jQuery, I’m comfortable using jQuery, so I use it to write a lot of my client-side code.
Anyway, so let’s say that there’s a
select element on the front-end of the website and it’s dynamically populated with a list of data. This could be a classification – that is, a list of taxonomies – or a list of posts (or posts of a certain type).
Next, assume that when the user selects an option from the
select element that it will redirect the current page of the browser to whatever page corresponds to the option they selected.
Finally, let’s say that once the user lands on the page to which they’ve been redirected, the option in the
select element should be set as the currently activate value of said element.
This carries three requirements:
valueattribute of the option is the URL to which the user should be directed
- The redirection is attached to the
changeevent of the
selectelement (which is managed via Select2)
- We need to set the active option in the Select2 element
The first two options are relatively simple to do; however, the third option is just a little more complicated. To achieve what we need to do we need to:
- Find the
selectelement on the page using the location of the current page
- Set the
selectelements value based on the URL of the page
Here’s a small function that shows how to do it:
Though the comments should make the code relatively clear here’s what’s happening:
- We grab the Select2 element by its ID
- We then attempt to grab an
optionbased on the page’s URL
- As long as the
optionexists, we then set the Select2 value equal to that option using one of its API functions
Easy enough, right?
And if you have multiple
select elements, then you can easily iterate over the collection of elements by using the
select2-container class name, looking at the ID attribute of the element, and then using the code snippet above.