Using the WordPress Media Library

WordPress-Logo

In one of my previous articles I talked about using the WordPress media uploader for your own plugins/themes. I had quite a few questions in the comments of that article about how to do certain things and to elaborate on the short code samples I gave. I also recently created a plugin for testing and illustrating how WordPress AJAX calls work. I found that this full plugin made it a lot simplier for people to go in and look at the code in action which led to a better understanding of what was going on.

For that reason I decided to do the same type of thing with the WordPress media library example I did. The plugin creates an admin page where you can save image URL from the media library into a table created by the plugin. Some key features that some people asked for such as image previews have been included in the plugin so you can see how they work as well. This way you can see the code run and then change it up to suite your specific needs.

The Code

You can download the code from my GitHub page which can be found here. Once you have it downloaded simply install it and take a look at how it runs. Run it a few times and follow along in the actual PHP/HTML/JS and you’ll quickly see how everything works (hopefully!).

Most of the code contains pretty basic things such as setting up an admin page and enqueuing scripts and styles. One of the more complex functions though is the creation of a custom database table. The code for that can be found below:

Basically this is the same as a normal MySQL statement that you would make, but first we just do a simple check to make sure that the table doesn’t already exist. I use this code as a template for whenever I have to create a custom table and I would recommend you do the same. Also you may notice the hook is the register_activation_hook( __FILE__, ‘dobdev_image_upload_tester_create_database_table’ );. This means this function will fire when the plugin is activated.

After that the plugin is pretty simple. I already talked about what everything does for the actual HTML and JS in my using the WordPress media uploader article so check that out if you need more information regarding the actual HTML form and JavaScript.

As always thank you for reading and please share it around as much as you can! Please feel free to put any suggestions or ideas for future tutorials in the comments section below.