Skip to content

Instantly share code, notes, and snippets.

@RadGH
Last active April 7, 2016 08:14
Show Gist options
  • Save RadGH/9144771 to your computer and use it in GitHub Desktop.
Save RadGH/9144771 to your computer and use it in GitHub Desktop.
WordPress media "browse" button
/*
HOW TO USE:
0. Ensure the admin page has enqueue the media library scripts. Here is an example to include it on the "Page" edit screen (post.php):
function page_enqueue_media_scripts() {
$screen = get_current_screen();
if ( $screen->base == 'post' && $screen->id == 'page' ) wp_enqueue_media();
}
add_action('admin_enqueue_scripts', 'page_enqueue_media_scripts');
1. Create a text input (or hidden input, or textarea, anything):
<input type="text" id="HELLOworld" value="" />
2. Create a button with class "media-browse" and attribute "data-media-url" which includes a selector pointing to the input above:
<a href="#" class="media-browse" data-media-url="#HELLOworld">Browse</a>
3. That's it! When you click browse and select an image, the image URL will be passed back to the input. This works for all "attachment" properties, including:
id, title, filename, url, link, alt, author, description,
caption, name, status, uploadedTo, date, modified,
menuOrder, mime, type, subtype, icon, dateFormatted,
nonces, editLink, sizes, height, width, orientation, compat
Tip: You can return the attachment ID, instead of a URL. Just change the attribute to "data-media-id".
All fields mentioned in #3 work this way. And when an image is selected/removed, we trigger "media-updated" and "change" on each field that is modified.
Tip #2: Create a "media-remove" button as a sibling of your browse button to remove media (Alternatively specify the browse button selector using the attribute "data-browse-button")
You don't need any other "data" attributes, the browse button will handle that!
*/
jQuery(function() {
var media_properties = ['id', 'title', 'filename', 'url', 'link', 'alt', 'author', 'description', 'caption', 'name', 'status', 'uploadedTo', 'date', 'modified', 'menuOrder', 'mime', 'type', 'subtype', 'icon', 'dateFormatted', 'nonces', 'editLink', 'sizes', 'height', 'width', 'orientation', 'compat'];
jQuery('.media-remove').on('click', function(e) {
e.preventDefault();
if (jQuery(this).attr('data-browse-button')) var $browse = jQuery(jQuery(this).attr('data-browse-button'));
else var $browse = jQuery(this).siblings('.media-browse');
if (!$browse.length) {
alert('No sibling browse button found, or the data-browse-button attribute had no matching elements');
return false;
}
$browse.data('attachment', false).trigger('attachment-removed');
// Trigger the update for the browse button's fields
for (i = 0; i < media_properties.length; i++) {
var media_key = media_properties[i];
var selector = $browse.attr('data-media-' + media_key); // data-media-url, data-media-link, data-media-height
if (selector) {
var $target = jQuery(selector);
if ($target.length) {
$target.val('').trigger('media-updated').trigger('change');
}
}
}
return false;
});
var file_frame;
jQuery('.media-browse').on('click', function(e) {
e.preventDefault();
var $this = jQuery(this);
if (!wp || !wp.media) {
alert('The media gallery is not available. You must admin_enqueue this function: wp_enqueue_media()');
return;
}
// If the media frame already exists, reopen it.
if (file_frame) {
file_frame.open();
return;
}
// Create the media frame.
file_frame = wp.media.frames.file_frame = wp.media({
title: $this.attr('data-media-title') || 'Browsing Media',
button: {
text: $this.attr('data-media-text') || 'Select',
},
multiple: false // Set to true to allow multiple files to be selected
});
// When an image is selected, run a callback.
file_frame.on('select', function() {
// We set multiple to false so only get one image from the uploader
attachment = file_frame.state().get('selection').first().toJSON();
// Extend this plugin yourself by binding the "attachment-selected" event to the button.
$this.data('attachment', attachment).trigger('attachment-selected');
// Allow each file property to be assigned to a field. Fields are referenced by the button's data attrbiutes
// All methods support a data attribute.
// data-media-{index}
// Example:
// attachment.url is assigned to the element matching the value of the "data-media-url" attribute (if available)
for (i = 0; i < media_properties.length; i++) {
var media_key = media_properties[i];
var selector = $this.attr('data-media-' + media_key); // data-media-url, data-media-link, data-media-height
if (selector) {
var $target = jQuery(selector);
if (!$target.length) {
if (console && console.log) {
console.log('Selector contains zero matched elements:', selector, 'Value expected:', attachment[media_key]);
continue;
}
}
// Assign the target field the given value, and trigger two events for developers to check for
$target.val(attachment[media_key]).trigger('media-updated').trigger('change');
}
}
});
// Finally, open the modal
file_frame.open();
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment