Use WordPress 3.5 new Media Uploader for your plugin and theme options panel development
As you all may have noticed, since WordPress 3.5 the CMS got a lot of enhancements especially regarding the user interface which surely looks sexier and one of the most noticeable changes is the new Media Uploader.
Whether you are developing a plugin or creating options panel for your theme, you want to use the new Media Uploader because you want to offer your users a seamless user experience through all sections of WordPress admin panel, on the other side, it’s easier than the old thick box media uploader to implement and work with.
First of all, let’s prepare the view, you may have something similar to the following:
1 2 3 4 5 6 |
<div> <label for="image_url">Image</label> <input type="text" name="image_url" id="image_url" class="regular-text"> <input type="button" name="upload-btn" id="upload-btn" class="button-secondary" value="Upload Image"> <span class="description">Uploading an image using the new WordPress 3.5 Media Uploader</span> </div> |
Your form may look like this:
Create a javascript file “custom-script.js” and copy and paste the following code to it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
jQuery(document).ready(function($){ $('#upload-btn').click(function(e) { e.preventDefault(); var image = wp.media({ title: 'Upload Image', // mutiple: true if you want to upload multiple files at once multiple: false }).open() .on('select', function(e){ // This will return the selected image from the Media Uploader, the result is an object var uploaded_image = image.state().get('selection').first(); // We convert uploaded_image to a JSON object to make accessing it easier // Output to the console uploaded_image console.log(uploaded_image); var image_url = uploaded_image.toJSON().url; // Let's assign the url value to the input field $('#image_url').val(image_url); }); }); }); |
The hard work is now done, in order for this to work, we need to enqueue the following scripts
1 2 3 4 5 6 |
// jQuery wp_enqueue_script('jquery'); // This will enqueue the Media Uploader script wp_enqueue_media(); // And let's not forget the script we wrote earlier wp_enqueue_script('custom-script.js'); |
That will be it! This is a very basic example, if you need more flexibility over the Media Uploader you may need to read more about the options you pass to wp.media. Please don’t hesitate to comment if you have a better way to do it.