In the options of that page, i would like to add a button that allow me to open the Wordpress media library and select an image from it, after that, get the URL of the selected image and the alt
attribute.
First you would need to enqueue wordpress core media scripts and a custom js script
function my_enqueue_media_lib_uploader() {
//Core media script
wp_enqueue_media();
// Your custom js file
wp_register_script( 'media-lib-uploader-js', plugins_url( 'media-lib-uploader.js' , __FILE__ ), array('jquery') );
wp_enqueue_script( 'media-lib-uploader-js' );
}
add_action('admin_enqueue_scripts', 'my_enqueue_media_lib_uploader');
Then let say you have this markup within your options page: an upload button and a text input to store the selected image url
<form method="post">
<input id="image-url" type="text" name="image" />
<input id="upload-button" type="button" class="button" value="Upload Image" />
<input type="submit" value="Submit" />
</form>
You need to add this javascript code to invoke the uploader popup
jQuery(document).ready(function($){
var mediaUploader;
$('#upload-button').click(function(e) {
e.preventDefault();
// If the uploader object has already been created, reopen the dialog
if (mediaUploader) {
mediaUploader.open();
return;
}
// Extend the wp.media object
mediaUploader = wp.media.frames.file_frame = wp.media({
title: 'Choose Image',
button: {
text: 'Choose Image'
}, multiple: false });
// When a file is selected, grab the URL and set it as the text field's value
mediaUploader.on('select', function() {
attachment = mediaUploader.state().get('selection').first().toJSON();
$('#image-url').val(attachment.url);
});
// Open the uploader dialog
mediaUploader.open();
});
});
Once the image is selected, your image-url input will now contain the url and will be saved on form submit.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With