Created
October 23, 2019 23:28
-
-
Save Cheslab/1559ea9ee861de12989b6340939f8d65 to your computer and use it in GitHub Desktop.
WordPress Media Library with pre-selected items
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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