One of the nicest features of WordPress 3.5 was the introduction of a refresh of the WordPress Media Uploader.
Sometimes, one of the challenges that comes with working with any new feature is the lack of documentation around how to take advantage of it. When that happens, you’re more or less left to dig into the core source code and/or the documentation for each of the specific libraries to learn how to use them.
The WordPress Media Uploader
When working on the Pressware Image Widget, one of the things I knew I wanted to take advantage of was the new WordPress media uploader.
Not only did it provide an opportunity to learn how to work with some new libraries, but it also helped make sure the user was able to add an image using an interface that was consistent with the rest of WordPress.
To be clear, I wouldn’t say I have a solid understanding or even any significant experience with Backbone or Underscore – instead, I’d say I’ve learned how to use them within the context of WordPress and under a very specific implementation at that.
Anyway, creating your own implementation of the WordPress media uploader isn’t terribly difficult. The problem is, right now, there’s not a lot of information for how to do it, so I thought I’d share how I implemented it within the Image Widget.
At the very least, it provides code you can drop into a project for tinkering or for extending for a something of your own.
Most of the time, I like to try to explain what the code is doing within the actual post, but, in this case, I’ve heavily commented the code. I did this primarily for my own benefit, but it saves some characters here in the post.
Just so you have some context to the code, here’s the general outline of what it’s doing:
- Define a handler to display the uploader when the DOM is ready. As the code says, you’ll actually want to change this in a production-level implementation.
- If an instance of the
file_frame, which is a reference to our media uploader, has been defined, then we can go ahead and open it; otherwise, it needs to be created.
- Setup a handler such that when an image is selected, we dump the properties (that is, their key and value pairs) to the console.
- We open the the media uploader.
As mentioned, the code is heavily commented so it should be clear enough to follow.
2. Include the Scripts
This is what you’d place in a plugin or in a theme functions file. Obviously, I’ve opted for the latter as far as this example is concerned.
This is a really really basic implementation of the WordPress media uploader. There are other implementations that already exist in core that allow you to insert galleries, insert multiple images, get more image details, and so on.
Clearly, that’s not covered here – perhaps another post – but hopefully this provides a stronger foundation off of which to work with the new media uploader.