Code to Open Media Gallery Dialog in WordPress
In a previous tutorial, we added an custom admin options page for WordPress where the admin can enter an copyright notice (in WP Dashboard -> Settings -> Copyright). And it would end up being displayed in the footer of the site. …
We will expand upon this and add the ability for the admin to choose an image from the Media Gallery to display in the footer.
The code from the previous tutorial to set the copyright notice is placed at the bottom of the theme’s functions.php file like so…
Enqueue script
Now add to the bottom of functions.php the following …
This will add footer_media.js as one more script for WordPress to load. This script has a dependency on jquery and will load at the bottom of the file (due to true in the last param).
Creating the footer_media.js file
Next we have to create footer_media.js file in the theme’s js folder …
Run the frontend and the admin dashboard in your browser and see that console log is output. This means that our jQuery code in footer_media.js is invoked properly.
Button to Open Media Library
We want to invoke the opening of the Media Gallery when the “Footer Image” button in the admin option page is clicked. But first we have to create the “Footer Image” button. In the code that constructs the “admin option” page, we add …
Button looks like this on the admin options page …
It has an id of “insert-footer-image”. But it doesn’t do anything. Until we write the following code in footer_media.js …
The jQuery code is invoked when button of id “insert-footer-image” is clicked. Then it builds an “gallery_window” object using wp.media passing in the properties value of the window to build.
We call the open() method of the newly constructed gallery_window object to open the media gallery dialog.
But a test run gives javascript error indicating that wp.media is undefined.
This is fixed by calling wp_enqueue_media like so …
Now the media gallery should pop up …
Note that the gallery title was one of the property values we passed into wp.media. We set “multiple” to “false” so that user can only select one image.
But how do we determine which image was selected? When the select event happens with gallery_window, we get its state and get its first selection and then convert toJSON() …
This gives us an object in user_selection with properties revealed in the console log when we do the for loop. Particularly useful is the url property which we retreive and pass to the text input box with id of “image-url”. This text input box, we forgot to put in the admin option page earlier, but we put it now …
In order for the values in the textbox to save, we have to …
Now in your template you can echo out the path of the selected image with …
echo get_option(‘footer_image’);