Skip to content

Instantly share code, notes, and snippets.

@fmtarif
Forked from huntlyc/hs-img-upload.js
Created October 15, 2013 12:30
Show Gist options
  • Save fmtarif/6990868 to your computer and use it in GitHub Desktop.
Save fmtarif/6990868 to your computer and use it in GitHub Desktop.
/**
Uploading files
Taken from: http://mikejolley.com/2012/12/using-the-new-wordpress-3-5-media-uploader-in-plugins/
INSTRUCTIONS:
In the page you wish to use this script you'll need to enque the media scripts and this script.
Then create a input box and a button with NOTHING in between.. with the class 'upload_image_button'
<?php
wp_enqueue_media();
wp_enqueue_script( $handle = 'hs-img-uploader',
$src = get_bloginfo('template_url') . '/admin/js/hs-img-upload.js',
$deps = array('jquery'),
$ver = false,
$in_footer = true );
?>
...
<input type="text" class="regular-text" id="Thumb" name="Thumb"><button class="button-secondary upload_image_button">Browse...</button>
**/
//File Upload vars
var file_frame;
var wp_media_post_id = (wp.media == undefined) ? null : wp.media.model.settings.post.id; // Store the old id
var set_to_post_id = 2; // Set this (from experminentation has to be a valid ID)
var jButton = null;
jQuery(document).ready(function(){
jQuery('.upload_image_button').live('click', function( event ){
event.preventDefault();
jButton = jQuery(this);
// If the media frame already exists, reopen it.
if ( file_frame ) {
// Set the post ID to what we want
file_frame.uploader.uploader.param( 'post_id', set_to_post_id );
// Open frame
file_frame.open();
return;
} else {
// Set the wp.media post id so the uploader grabs the ID we want when initialised
wp.media.model.settings.post.id = set_to_post_id;
}
// Create the media frame.
file_frame = wp.media.frames.file_frame = wp.media({
title: jQuery( this ).data( 'uploader_title' ),
button: {
text: jQuery( this ).data( 'uploader_button_text' ),
},
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();
// Do something with attachment.id and/or attachment.url here
jButton.prev('input[type="text"]').val(attachment.url);
jButton = null;
// Restore the main post ID
wp.media.model.settings.post.id = wp_media_post_id;
});
// Finally, open the modal
file_frame.open();
});
// Restore the main ID when the add media button is pressed
jQuery('a.add_media').on('click', function() {
wp.media.model.settings.post.id = wp_media_post_id;
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment