wp.media
is the JavaScript API WordPress uses to display the media library modal.
You can use it yourself by enqueueing a custom JS script on your admin page:
wp_enqueue_script('media-upload');
wp_enqueue_media();
wp_enqueue_script(
'pb-admin-script',
'admin.js',
array(
'jquery',
)
);
Then work with it like this:
HTML:
<button class="upload_image_button button button-primary">
<?php _e('Upload Image', 'pb'); ?>
</button>
<img src="" id="image-preview" style="display: none"/>
JS:
jQuery(document).ready(function($) {
$(document).on('click', '.upload_image_button', function(event) {
event.preventDefault();
var imgPrev = $('#image-preview');
var file_frame = wp.media.frames.file_frame = wp.media({
title: 'Select or upload image',
library: {
type: 'image'
},
button: {
text: 'Select'
},
multiple: false,
});
file_frame.on('select', function() {
var attachment = file_frame.state().get('selection').first().toJSON();
imgPrev.src = attachment.url;
imgPrev.style.removeProperty('display');
});
file_frame.open();
});
});