Recently I had to include a image selector in one of the plugins I was developing. Going for the pure WordPress look and feel, I really wanted to use the image selector everyone knows from the ‘Add Media’ button when you modify a post. To accomplish this, you’d need to go through a couple of steps I will lay out here.
Create a settings page
You may already have a settings page ready where you want to include the media selector on, if so, you can skip this step and go to the next one. Use the following code to add a new submenu page to the ‘Settings’ menu.
What this does is add a ‘Media selector’ link to the settings page, and uses the ‘media_selector_settings_page_callback’ function to display the setting fields.
And just to be clear, this will work, but is anything but the best way of adding a settings page. Please use the Settings API for that, and if you want to make it easy for yourself, generate a settings page with the WP Settings API tool.
Add the settings fields
In order for the media selector to fully work, you need at least a upload button and a input field. The input field can be a text field, but also a hidden field. In this post we’re inserting the post ID of the attachment that is being selected/uploaded, so I chose for a hidden field.
Include the (java)scripts
Right now you should have a page that you can visit, and see a button and a empty image. When clicking the button, nothing will happen as we still need to include some scripts. WordPress has made this very easy for us, and you can use the following code for that
- On the ‘#upload_image_button’ button click, it will open the media selector
- Set the image preview ‘src’ so the preview will be immediately visible
- Set the attachment ID in the hidden input field for us to save later
Save the selected image
I just realised I was missing a <form> tag and a save button on my settings page, so I added that below. Also adding a bit of code to save the attachment ID, and pre-filling the preview and input field when they are saved.
That should be it, you will now have a settings page, with a official WordPress media selector allowing you to select and save the attachment ID. I want to say again that the code is used to give a example on how to implement the WordPress media selector, not on how to create a proper settings page, enqueue scripts or anything.
Here’s a snippet with my entire test plugin;