WordPress 3.5 has been released recently, I used the WordPress Media Upload system via thickbox and window.send_to_editor
for some options in my WordPress theme (backgrounds, logos etc…).
But as you know WordPress has integrated a new Media Manager, I wanted to used this new feature to upload images/files as custom fields. So I spent the morning to find a way to get the wished result.
I found with this solution, which can be useful for some of you. Thanks to give me your feedback on the code or any improvements you have in mind!
HTML Sample:
<a href="#" class="custom_media_upload">Upload</a>
<img class="custom_media_image" src="" />
<input class="custom_media_url" type="text" name="attachment_url" value="">
<input class="custom_media_id" type="text" name="attachment_id" value="">
jQuery Code:
$('.custom_media_upload').click(function() {
var send_attachment_bkp = wp.media.editor.send.attachment;
wp.media.editor.send.attachment = function(props, attachment) {
$('.custom_media_image').attr('src', attachment.url);
$('.custom_media_url').val(attachment.url);
$('.custom_media_id').val(attachment.id);
wp.media.editor.send.attachment = send_attachment_bkp;
}
wp.media.editor.open();
return false;
});
If you want to see every settings contained in the attachment
variable you can do a console.log(attachment)
or alert(attachment)
.
Your going about it in a way that was unintended. Your javascript code should probably look something like this:
Don’t forget to use
wp_enqueue_media
(new in 3.5) if you’r not on the post edit pageTo use the old media upload box you can do this:
I modified this code a bit more to make it usable for multiple fields at once:
HTML:
jQuery:
I found nothing to trigger a custom function if the editor closes. I uses this:
or better:
I haven’t had much chance to play with this, but for those looking to leverage the gallery element, this code should set you on your way.
It is just a start point – it only provides a comma separated list of image id’s, but that should be enough to start being creative.
This will populate the input field with a comma separated list of the image id’s, in the order they were set in the editor (using the new drag and drop functionality).
The function expects the shortcode to be sent back for placement in the main editor, but we don’t want to do this, so we create a new object that returns a blank string for insertion.
Also note, this doesn’t handle inserting a single image as described above – it’ll just put it into the post editor. So try combining the two listeners, or remove the appropriate tabs.
EDIT
Having spent some time looking at the core, I think this whole process can actually be done easier using the technique laid out here, but as you’ll read I haven’t figured out yet how to pre-select the images when you reopen the media manager.