If you are creating a WordPress plugin that requires your users to select or upload media from the plugin options page, it is a good idea to include the one that people feel familiar with. The core WordPress Media Uploader is relatively easy to implement and the user-friendly interface should make your users feel comfortable while uploading media.
For the purpose of this post I am going to assume you already have an options page for your plugin. If you don’t, there are plenty of tutorials on the web to help you achieve this. The code contained within this article was used in a lightweight plugin I developed to allow users to customise their WordPress login page.
media-uploader.js (or similar) within the plugin folder. Place the following code in it and save.
When called by the
#upload_image_button, this script launches the native WordPress Media Uploader interface and inserts the chosen file in the destination field
As an example, in my plugin the destination field gets saved in the plugin options as the background image for the login page.
The function code.
Next, we need to register the script and enqueue it using the following code in the main plugin file:
Registering and enqueueing lets the WordPress core know where the script is located and any dependencies it has.
wp_register_script has a number of parameters:-
wp_register_script( $handle, $src, $deps $ver $in_footer)
$handleis what you use to refer to your script
$srcpath to the file within your plugin – use
plugins_url(‘your-file.js’, __FILE__)to get the URL root of the plugin
$depsan array of registered script handles that this script depends on
$verscript version number
$in_footeroption to enqueue the script before the closing
</body>tag instead of in the
See the WordPress Functions Reference for a more detailed description of these.
Both scripts and styles are properly enqueued by attaching the function to the
admin_enqueue_scripts hook. Note that we are using the admin hook rather than
wp_enqueue_scripts as we are not dealing items that appear on the front-end.
add_action hook allows us to specify precisely at what point the defined function is added during script execution.
The form code.
Lastly, we need to add a couple of fields to our plugin options page – a button that calls the Media Uploader script and a text field that saves the URL of the image to the database:
As you can see, for my plugin I have registered a setting on the options page called
background_image which is selected using the Media Uploader.
I have also given the Insert Image button the
button-primary class to maintain the default WordPress look.
Adding the familiar native WordPress media uploader to your plugin options page should be relatively straightforward.
In my next post, I will explain how to add the native WordPress color picker for use on your plugin options page.