UPDATED – scroll down
After too much of hard work and research and some customization I coded below compact few lines of code to use media uploader anywhere in wordpress. Just put code in some function and call that function wherever you want.
The path of uploaded/selected file will be copied to text-box and then you can use it.
// jQuery
wp_enqueue_script('jquery');
// This will enqueue the Media Uploader script
wp_enqueue_media();
?>
<div>
<label for="image_url">Image</label>
<input type="text" name="image_url" id="image_url" class="regular-text">
<input type="button" name="upload-btn" id="upload-btn" class="button-secondary" value="Upload Image">
</div>
<script type="text/javascript">
jQuery(document).ready(function($){
$('#upload-btn').click(function(e) {
e.preventDefault();
var image = wp.media({
title: 'Upload Image',
// mutiple: true if you want to upload multiple files at once
multiple: false
}).open()
.on('select', function(e){
// This will return the selected image from the Media Uploader, the result is an object
var uploaded_image = image.state().get('selection').first();
// We convert uploaded_image to a JSON object to make accessing it easier
// Output to the console uploaded_image
console.log(uploaded_image);
var image_url = uploaded_image.toJSON().url;
// Let's assign the url value to the input field
$('#image_url').val(image_url);
});
});
});
</script>
UPDATE: Just to add. You may need to add the function wrapper in your plugin/theme file. This is the following:
// UPLOAD ENGINE
function load_wp_media_files() {
wp_enqueue_media();
}
add_action( 'admin_enqueue_scripts', 'load_wp_media_files' );
This will call the relevant JS files and CSS files if WP fails to load the upload manager. This also removes console warnings.