Skip to content

Instantly share code, notes, and snippets.

@stalukder03
Forked from Cheslab/upload.js
Created June 28, 2022 05:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stalukder03/0cc61641b21fce2e3ef5b0c1e7e2eff5 to your computer and use it in GitHub Desktop.
Save stalukder03/0cc61641b21fce2e3ef5b0c1e7e2eff5 to your computer and use it in GitHub Desktop.
WordPress Media Library with pre-selected items
/**
* Utilize WordPress' media library. Easy select/upload files for your plugin/theme admin page.
* It uses build-in jQuery 1.4.1
* Tested with WordPress 5.2.4
*/
$('.my-upload-button').click(function(e) {
e.preventDefault();
// setup our media library frame
let frame = wp.media({
title: 'Upload your pictures',
multiple: true, // allows user to select multiple files at once
library: {
type: 'image', // if you need only images
},
});
// if you have IDs of previously selected files you can set them checked
frame.on('open', function() {
let selection = frame.state().get('selection');
let ids = [13, 14, 56]; // array of IDs of previously selected files. You're gonna build it dynamically
ids.forEach(function(id) {
let attachment = wp.media.attachment(id);
selection.add(attachment ? [attachment] : []);
}); // would be probably a good idea to check if it is indeed a non-empty array
});
// get the URLs of the selected items
frame.on('select', function() {
let selection = frame.state().get('selection');
let images = [];
selection.models.map(function(image) {
images.push({
id: image.attributes.id,
url: image.attributes.url,
});
});
console.log(images);
});
// open wp media library frame
frame.open();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment