Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress - Get an image using the media library

I'm creating a plugin and i have an admin page

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.

If it is possible, how can i do that using AJAX?

like image 563
Rodrigo Calix Avatar asked Oct 01 '15 16:10

Rodrigo Calix


1 Answers

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.

like image 190
PrismoSoft Avatar answered Nov 09 '22 20:11

PrismoSoft