How to use WordPress 3.5 media uploader in wordpress themes, theme option or plugin

WordPress
How to use WordPress 3.5 media uploader in wordpress themes, theme option or plugin

Here is a simple tip. Sometime we need to add WordPress file uploader in our theme, theme option or plugin files. For example in theme option we create an interface for changing the favicon of the site, then we need a file uploader with WordPress media library. So here we can use WordPress custom file uploader.You can add a WordPress file uploader to your theme or plugin with the following steps:
Include the following jquery :

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> 

<script type="application/javascript">

 jQuery(document).ready(function($){

	var _custom_media = true,

	_orig_send_attachment = wp.media.editor.send.attachment;

	$('.btn_upload').click(function(e) {

	var send_attachment_bkp = wp.media.editor.send.attachment;

	_custom_media = true;

		wp.media.editor.send.attachment = function(props, attachment)

		{

			if ( _custom_media ) 

			{

				$("#txt_imgurl").val(attachment.url);

			} 

			else 

			{

				return _orig_send_attachment.apply( this, [props, attachment] );

			}

		}

	wp.media.editor.open(this);

	return false;

	});

});

</script>

Write this code in functions.php

   < ?php if(function_exists( 'wp_enqueue_media' )){ wp_enqueue_media(); }else{ wp_enqueue_style('thickbox'); wp_enqueue_script('media-upload'); wp_enqueue_script('thickbox'); }?>

Create form element for uploading :

<input type=”text” name=”txt_imageurl” id=”txt_imageurl” />

<input type=”button” class=”button_upload” name=”btn_upload” id=”btn_upload” value=”Upload” />

Leave a Reply

Your email address will not be published. Required fields are marked *

8 + twenty =

2hats Logic HelpBot