WordPress has a nice media uploader dialog that it uses on the editor pages. Now wouldn’t it be nice if you could use it to handle image uploads for part of a plugin or theme you’re writing? Maybe you want to add an easy way to change the logo in a theme? A simple “Upload Image” button would work quite well for that, wouldn’t it?

It’s fairly simple to implement, providing you already have a bit of experience with the WordPress API.
The first step is to prepare your HTML. Put it wherever the code for your admin page is. You want to have a text input for the image URL, and a button that will launch the uploader dialog.
<tr valign="top"> <th scope="row">Upload Image</th> <td><label for="upload_image"> <input id="upload_image" type="text" size="36" name="upload_image" value="" /> <input id="upload_image_button" type="button" value="Upload Image" /> <br />Enter an URL or upload an image for the banner. </label></td> </tr>
Now that the easy part is out of the way, it’s time to start making it do something. You need to enqueue some scripts and styles. Here’s an example function to show how it’s done:
function my_admin_scripts() {
wp_enqueue_script('media-upload');
wp_enqueue_script('thickbox');
wp_register_script('my-upload', WP_PLUGIN_URL.'/my-script.js', array('jquery','media-upload','thickbox'));
wp_enqueue_script('my-upload');
}
function my_admin_styles() {
wp_enqueue_style('thickbox');
}
if (isset($_GET['page']) && $_GET['page'] == 'my_plugin_page') {
add_action('admin_print_scripts', 'my_admin_scripts');
add_action('admin_print_styles', 'my_admin_styles');
}
We need the media-upload and thickbox scripts for starters, as well as jQuery, which is already included. Then we have to register and enqueue our own JavaScript file, my-script.js, which will handle the media uploader functionality. We also need to load the thickbox stylesheet in the next function.
The if (…) block ensures that the scripts and styles will only be included if the user is on a specific admin page. If you look at your plugin’s (or theme’s) admin page, the URL should have a ?page=some_string at the end. Substitute my_plugin_page for that string.
Now for the part the actually invokes the uploader: the JavaScript. This will go in the my-script.js file we included earlier.
jQuery(document).ready(function() {
jQuery('#upload_image_button').click(function() {
formfield = jQuery('#upload_image').attr('name');
tb_show('', 'media-upload.php?type=image&TB_iframe=true');
return false;
});
window.send_to_editor = function(html) {
imgurl = jQuery('img',html).attr('src');
jQuery('#upload_image').val(imgurl);
tb_remove();
}
});
The first click() event listener opens a ThickBox dialog when the “Upload Image” button is clicked, and loads the uploader page inside it. It also stores the name of the URL input field in a variable, for later use.
The second function overrides the send_to_editor() function in the media-upload script. This is probably the most important part. When the “Insert into Post” button is clicked in the uploader dialog, this function fires. It collects the URL of the image that was uploaded, dumps it into the awaiting form field, and closes the ThickBox dialog.
That’s it. Providing everything went according to planned, you should have a form field that will either accept an arbitrary image URL, or allow a user to upload one on the spot.

Update: If you want to use the fancy new media uploader introduced in WordPress 3.5, be sure to check out the revised and updated post that covers it.












Very cool – It looks like WordPress theme creators are spending more and more time on the details, and of course the ability to easily swap out the logo in a theme is a great little feature.
Don’t forget plugin creators! I put this post together because I was working on a plugin. I figured out how to do it by studying a couple of plugins that had upload features.
May have to test drive this into my Custom Login theme.
Thanks for the article. It really got me thinking
May sound like a stupid request, but could you provide a ‘generic’ plugin with nothing more than the input box in the admin page, along with the way I would call that image in my template?
I was thinking of trying this idea to allow my user to upload the background image for their theme as a starter, and if I can see how that works, then I’m pretty sure I can hack the code to use it in other places.
I don’t really want to be maintaining another plugin at this point.
However, the code I provided above is fairly nonspecific, and should be possible to fit into any application, giving some work. It would require some PHP/WordPress experience though.
However, if you’re looking for a quicker solution, you might try looking at existing themes or plugins with uploader capabilities. I think Kubrick, the default WP theme, might have a similar uploader (?) to allow users to add a background image to the header. I may not be remembering correctly about Kubrick, but I know there are several themes that offer functionality along those lines. I should be trivial to borrow some code from the themes and insert it into your functions.php.
Wow, that’s great. Thank you! Will use it for a Client Website, so he can change the Logo easily.
You should try the theme options framework from UpThemes. It is built specifically for theme developers who wish to add logo/image/color options to their themes. There is also a lot more that you can accomplish with the framework. It’s GPL, so you can make it your own with your branding.
I managed to get this working on my site, but I have one quick question if you don’t mind.
How do I change it from a single image selection to an array of selections?
Meaning, my theme has a logo, page background, and a footer background. I would like to have a page with 3 uploaders so that the user can select an image for each field.
I tried replicated the code 3x on the same page, but that just threw up a ton of errors.
Another reader worked out a way to have multiple uploaders: http://www.theenglishguy.co.uk.....tions-php/
Just make sure you give the input tags different name and id attributes.
How do I automatically upload multiple images selecting multiple images with uploader?. Colud I, for example, fill a list box with all images uploaded through uploader?. I mean I don’t want to use multiple uploaders as the post you have shown.
If you wanted to populate some other type of form field with more than one URL, you could, but you would have to figure out your own script. You would need to use jQuery to append instead of replace the form text.
Or to use the add_attachment filter. I managed to automatically add the ID of each image uploaded to my own database. Thanks.
This is so great . I was looking for that
How can I use it in Theme option or custom meta box in post ?
hope to found the answer .
Thanks alot
Sub
You can use it wherever you want, providing you queue-up the requisite scripts. So, yes, it would work fine in either a meta box or an options page.
Awsome thanks! With these guidelines I could quite easily implement this.
First I tried getting some other jquery uploader and image crop tool working, but when the WP supplied tools work – and is easily implementable like you guided – then imho its clearly best to use them.
How can this be done with a custom meta box and not screw up the regular media uploader? Right not it will automatically pull anything you try to use in the post even if your not trying ot use the custom meta box/field.
It should depend on what ids you use for the form and script.
Mind providing an example that would work? I basically just used your example, which didnt as it obviously conflicted like i mentioned before. Thanks for the help. I appreciate it.
I looked over the code again, and I think your problem might be because the script overrides the window.send_to_editor function from the uploader. My JS skills aren’t really sufficient to prescribe a solution for your scenario, but you might want to look into something like this:
http://stackoverflow.com/quest.....e-original
I’ve come up with this code to allow for the original send to editor to work.
jQuery(document).ready(function() {
var formfield;
jQuery(‘#Image_button’).click(function() {
jQuery(‘html’).addClass(‘Image’);
formfield = jQuery(‘#Image’).attr(‘name’);
tb_show(”, ‘media-upload.php?type=image&TB_iframe=true’);
return false;
});
/*
window.send_to_editor = function(html) {
if ( jQuery(‘html’).hasClass(‘Image’) ) {
imgurl = jQuery(‘img’,html).attr(‘src’);
jQuery(‘#Image’).val(imgurl);
tb_remove();
jQuery(‘html’).removeClass(‘Image’);
}
}*/
// user inserts file into post. only run custom if user started process using the above process
// window.send_to_editor(html) is how wp would normally handle the received data
window.original_send_to_editor = window.send_to_editor;
window.send_to_editor = function(html){
if (formfield) {
fileurl = jQuery(‘img’,html).attr(‘src’);
jQuery(‘#Image’).val(fileurl);
tb_remove();
jQuery(‘html’).removeClass(‘Image’);
} else {
window.original_send_to_editor(html);
}
};
});
Which I modified from the code snippet
If it’s of use for anybody, here’s my version.
/**
* Trigger upload dialog
*/
jQuery(document).ready(function() {
var header_clicked = false;
jQuery(‘#upload_image_button’).click(function() {
formfield = jQuery(‘#upload_image’).attr(‘name’);
tb_show(”, ‘media-upload.php?type=image&TB_iframe=true’);
header_clicked = true;
return false;
});
// Store original function
window.original_send_to_editor = window.send_to_editor;
/**
* Override send_to_editor function from original script
* Writes URL into the textbox.
*
* Note: If header is not clicked, we use the original function.
*/
window.send_to_editor = function(html) {
if (header_clicked) {
imgurl = jQuery(‘img’,html).attr(‘src’);
jQuery(‘#upload_image’).val(imgurl);
header_clicked = false;
tb_remove();
} else {
window.original_send_to_editor(html);
}
}
});
Matt!!!
Thank you very much, dude. Your tips was extremely helpful for me to implement my “featured” plugin. I searched all over the internet for this, and thanks Godgle I found your post.
Now my little plugin is just rocking.
Thanks again!
Saved me a lot of work. Thanks!!!!!!
Great tutorial, works perfectly.
Is there a way to use this for other media types (specifically PDF)? I understand everything but the javascript, and can’t seem to pinpoint what to change in there.
Thanks again for great tutorial.
Okay, I finally figured it out, and everything seems to work this way.
I changed this line:
imgurl = jQuery(‘img’,html).attr(‘src’);
to this:
imgurl = jQuery(html).attr(‘href’);
Works as far as I can tell.
Thanks Kirk
just what i needed!
and Matt great post, works really well.
Freaking Yes!!! Exactly what I needed for several websites. Thanks.
Awesome dude! This was exactly what I was looking for and it’s so easy! Find & Replace
Thank you so much for this info!
Works like a charm ! Thank you.
Thanks.. Works perfectly
It’s a great way to integrate WP upload box to my plugin. Thanks for sharing.
do not work under 2.9.2?
it seems that the send_to_editor function has never been called…
hi!
thanks for your great article.
i wondering how hard to search the web for wordpress references, google always give me irrelevant results.
for example, i want to know which kind of types are allowed:
“media-upload.php?type=”
maybe i can see through bunch of php codes, but it could be great, if the media library documented.
can you help me with a link to this?
Hey,
Any way this can be used for a front-end custom post form?
Thanks
Probably, but I wouldn’t recommend it. Front-end uploaders need additional security checks. You need to verify that the item being uploaded is the type of file you expect (and simply checking for a .jpg or .png extension isn’t enough). Otherwise someone could upload what amounts to malware.
Matt – I understand the need to be cautious, but doesn’t WordPress now handle those security checks already, regardless of whether the upload occurs in the frontend or not?
For example : http://www.h-online.com/securi.....45416.html
What are your thoughts on this?
It’s probably not too much of an issue. It still does open up more potential for exploits, but the risk probably isn’t terribly great.
So all files keep in wp-content/uploads folder?
how to change it?
regards
thanks
Hi Matt, Thanks you very much for sharing this script, you are a GOD sent for me.
Copied your code and added it to Datafeedr Random Ad V2 where I would like to add an upload image option instead of pasting the image as html. Somehow the upload button does not invoke anything at all. Would that be because of the way I adjusted the function:
function my_admin_scripts() { // load necessary script including new script
wp_enqueue_script(‘media-upload’);
wp_enqueue_script(‘thickbox’);
wp_register_script(‘my-upload’, get_bloginfo(‘wpurl’) .’/wp-content/plugins/datafeedr-ads/my-script.js’, array(‘jquery’,'media-upload’,'thickbox’));
wp_enqueue_script(‘my-upload’);
}
and the fact that I added the code later on in the script?
You have the add_action() hooks calling the function, right? I don’t see anything jumping out at me that would cause it to fail…
I use these actions:
if (isset($_GET['page']) && $_GET['page'] == ‘datafeedr-ads’) {
add_action(‘admin_print_scripts’, ‘my_admin_scripts’);
add_action(‘admin_print_styles’, ‘my_admin_styles’);
}
Maybe the page datafeedr-ads should be added differently in the first line?
Been using this successfully on a plugin I’ve written, but when testing on WordPress 3.0 beta 2, I’m not actually getting an “Insert into Post” button on the media uploader.
Anyone else having the same problem?
@ Owen Been trying to add it to datafeedr random adds without any luck: http://wordpress.pastebin.com/yprywP7J Any ideas what I am missing? I would really appreciate your insight..
This is a great article! It works perfectly on my plug-in.
I’m wondering if its possible to implement Amazon S3 on this?. any ideas?
thanks,
I don’t know. There are some plugins that somehow commandeer the uploader and send the files to S3, I believe. You might take a look at their code, if I you can find one.
I suppose one way would be to temporarily upload the file and have the callback pass the file path to a script that copies it to S3 and then deletes it from the local server (returning the new S3 URL, of course).
Great tutorial. but i one problem my form field doesn’t accept an arbitrary image URL.
I think line 11 doesn’t assign the value(imgurl) on the id (#upload_image). any idea what am i missing?
09 window.send_to_editor = function(html) {
10 imgurl = jQuery(‘img’,html).attr(‘src’);
11 jQuery(‘#upload_image’).val(imgurl);
12 tb_remove();
13 }
Matt, how can i unsubscribe comments?
There should be a link in the emails.
Matt, I think it doesn’t work on the later versions of wordpress or am i just missing something? because I try the code above under wordpress 3.0 beta 2, it seems that the send_to_editor function has never been called.
any success on the latest version? thnx
I haven’t tested it on the 3.0 builds yet. I may give it a look when I have time. (The only place I’m using the code is in a plugin I’ve been working on, and I don’t want to upgrade the development environment until 3.0 goes gold.)
I’m also implementing this code on the plugin that im currently woring on, it works like a charm and i was able to upload the image but this code below doesn’t seem to work as expected.
window.send_to_editor = function(html){
imgurl = jQuery(“img”,html).attr(‘src’);
jQuery(“#upload_image”).val(imgurl);
tb_remove();
}
Anyone else having the same problem?
you probably are missing your STYLESHEET file.
how can I define where the media should be uploaded to? Lets say I want to have it in images/abc/
bascically, I want the uploader to only upload to images/abc/
is that possible?
thanks
/aleto
I don’t know. I haven’t explored it that far yet. It’s probably possible.
How can I get the gallery tab to show up after uploading multiple images and then saving. With the regular editor when you click save it loads the gallery tab. I don’t have a textfield just an upload submit button.
Any help would be great. Thanks for the great tutorial.
MB
Or how can I get the post id into the “media-upload.php” line in the JavaScript?
original…
media-upload.php?type=image&TB_iframe=true
would like…
media-upload.php?post_id=$post->ID&type=image&TB_iframe=true
Really I would like to insert a gallery into a custom field. Can I do that?
Thanks again.
First up, cracking article. Thank you. However, on WordPress 3.0 there is a small problem as several people have pointed out above. When you upload an image you don’t get the ‘insert into post’ button to press. However, once you’ve uploaded an image, it’s in the ‘media library’ tab. So if you click on that and then press ‘show’ next to the relevant image, you THEN get the option to insert into post.
So your code DOES work, however it’s not the most user-friendly at the moment. My javascript skills are somewhat limited (read as: pathetic), so I’m not sure how’d you fix this, but I can think of two possible options:
1) Override the ‘save all changes’ button instead of the insert into post – because this button DOES show up, but the ‘insert into post’ button doesn’t
2) Add an ‘insert into post’ button next to the ‘save all changes’ button manually using some jQuery magic.
Hopefully this feedback helps a little, I’d love to know if you come up with a way around this!
I’m not an expert at JavaScript voodoo either.
It might be fun to play around with this some more, but I’ve been busy to the point that I haven’t even managed to test my plugins on 3.0. (I haven’t upgraded any of my blogs yet, either.)
Just for reference I’ve opened up a thread on the WordPress.org forums:
http://wordpress.org/support/topic/412979
Hopefully someone with some javascript awesomesauce can sprinkle some magic dust and make this work
I found a solution, albeit a hack-ish one, for the absence of the inset into post button. Just comment out or delete line 1267, if ( $send ) in /wp-admin/includes/media.php
As I said, it’s a hack and updates will likely overwrite the change, but it works. This functionality is important in the site I am currently building, so I will keep digging for a better solution.
An absolute ninja friend of mine who is wise in the ways of javascript (amongst many other disciplines) has hacked and scratched away and has come up with this as a replacement for your script.js file:
http://pastebin.com/tpwsY1iu
This ONLY works for the html uploader – i.e. it doesn’t work for the Flash uploader, mainly because the flash uploader doesn’t refresh the page.
However, this adds the ‘Insert’ button when a user uploads a file and passes the url back to your form when the button is pressed.
Tim, above, found a way to hack at core to get the button to display, however if, like me, hacking at core isn’t an option (I’m writing a plugin), then this may help you.
This could possible be extended by someone with some time finding out what function the Flash uploader calls and then writing some further javascript wrapper functions akin to the one in the file above.
You could also probably easily adjust it so that the ‘insert’ button is displayed always (i.e. before a file has been uploaded) and this would probably make it work for the flash uploader, too. Hope this helps! And I hope we get to a final conclusion soon!
Hey all.
I’d like to post my solution. I used it to exchange a picture in the header & I’d like to use the original Uploader in the article selection.
The main idea of this script is: I’m overwriting send_to_editor & tb_remove, but do also store the inital ones. Then I introduce a boolean var (header_clicked). This is set to true, if my plugin button (upload_image_button) is clicked. Then the new function is called, if it’s still false, the old one is executed.
Then I overwrite tb_remove, which just sets header_clicked to false and is exectuted, when the upload-dialog is closed. Thus: Everytime the upload dialog is started, the boolean is false (executing the original uploader), if it true (the plugin button is clicked), the alternative version is called.
Hope someone finds this useful.
/**
* Trigger upload dialog
*/
jQuery(document).ready(function() {
var header_clicked = false;
jQuery(‘#upload_image_button’).click(function() {
formfield = jQuery(‘#upload_image’).attr(‘name’);
tb_show(”, ‘media-upload.php?type=image&TB_iframe=true’);
header_clicked = true;
return false;
});
// Store original function
window.original_send_to_editor = window.send_to_editor;
window.original_tb_remove = window.tb_remove;
/**
* Override removing function (resets our boolean)
*/
window.tb_remove = function() {
header_clicked = false;
window.original_tb_remove();
}
/**
* Override send_to_editor function from original script
* Writes URL into the textbox.
*
* Note: If header is not clicked, we use the original function.
*/
window.send_to_editor = function(html) {
if (header_clicked) {
imgurl = jQuery(‘img’,html).attr(‘src’);
jQuery(‘#upload_image’).val(imgurl);
tb_remove();
} else {
window.original_send_to_editor(html);
}
}
});
For those with the “Insert Into Post” button problem in WP3: Turns out that the default WordPress upload link includes one more GET variable: the post ID. Once that is included, the “Insert Into Post” button shows up. This is the click function I’m using:
jQuery(‘#upload_image_button’).click(function() {
formfield = jQuery(‘#upload_image’).attr(‘name’);
post_id = jQuery(‘#post_ID’).val();
tb_show(”, ‘media-upload.php?type=image&TB_iframe=true&send=true&post_id=’+post_id);
return false;
});
Disregard the comment above. That will only work if your custom post type supports ‘editor’.
This code on line 1166 of /wp-admin/includes/media.php:
$default_args = array( ‘errors’ => null, ‘send’ => post_type_supports(get_post_type($post->post_parent), ‘editor’), ‘delete’ => true, ‘toggle’ => true….
just added some line to Matt’s js-script for to toggle between editor input and textfield. Works for me with WP 3 incl. “Insert Into Post” button”; postid is in container on the page.
jQuery(document).ready(function() {
var ww = jQuery(‘#post_id_reference’).text();
window.original_send_to_editor = window.send_to_editor;
window.send_to_editor_clone = function(html){
imgurl = jQuery(‘img’,html).attr(‘src’);
jQuery(‘#upload_image’).val(imgurl);
tb_remove();
}
jQuery(‘#add_image’).click(function() {
window.send_to_editor=window.original_send_to_editor;
tb_show(”, ‘media-upload.php?post_id=’ + ww + ‘&type=image&TB_iframe=true’);
return false;
});
jQuery(‘#upload_image_button’).click(function() {
window.send_to_editor=window.send_to_editor_clone;
formfield = jQuery(‘#upload_image’).attr(‘name’);
tb_show(”, ‘media-upload.php?post_id=’ + ww + ‘&type=image&TB_iframe=true’);
return false;
});
});
Thanks Norbert!
Keeping the editor’s uploader functional after adding a custom upload button was proving rather tricky for me. Thanks to you (and Matt, of course) it’s working now.
All-around great post and comments guys!
It sounds like a revamp of the Media Uploader is on the radar in trac. Keeping my fingers crossed…
This is the closest I’ve been thanks to you! That’s awesome. Although the Insert into Post button only seems to work when I click on Media Library, not in the window that pops open when I upload.
Thank so much for posting. Helped out a ton!
If you wanted to have more than one media upload button in the same page you can make in PHP in a loop (with $i):
Uploadimage
And in javascript :
jQuery(document).ready(function() {
var fileInput = '';
jQuery('.upload_image_button').click(function() {
fileInput = jQuery(this).prev('input');
formfield = nextInput.attr('name');
tb_show('', 'media-upload.php?type=image&TB_iframe=true');
return false;
});
jQuery('.upload_image').focusin(function() {
fileInput = jQuery(this);
formfield = jQuery(this).attr('name');
tb_show('', 'media-upload.php?type=image&TB_iframe=true');
return false;
});
window.send_to_editor = function(html) {
imgurl = jQuery('img',html).attr('src');
fileInput.val(imgurl);
tb_remove();
}
});
So you can have multiple inputs to upload images in the same page
This doesn’t seem to work for me??
Hey! Awesome article, I used this, but now it won’t allow me to insert images to a tinymce box…?
Any ideas on how to get both to work together?
See some of the above comments. It overrides something that breaks the normal post uploader.
Senica,
please try the code I modified from Matts post on July 1. It adds a click event
jQuery(‘#add_image’).click(function() {
to the standard editor box. That reinstalls the overwritten function.
So, you can insert images in the standard editor and in your textfield and vice versa
Please remind, that you have to put the WordPress Post ID in a location that can be accessed by jQuery.
I can’t do this work for me
The upload works but they don’t return nothing to my input.
Help please.
Andrea,
please read the above posts. The js script needs the post ID.
Find a workaround with Richard tapes post from June, 20th
Or use my js script from July 1st
I’ve been trying to use the “multiple” media uploader buttons script someone posted above, however I just can’t get it to work. I can get one to work, but no more than that. I’ve tried everything. Could someone please explain how to do it in an easier to understand version?
One thing I noticed…. You MUST leave the link url on the picture. If you take it off, it doesn’t work.
Thanks to you I was able to enable image upload to a plug – Runners Log – Im writing.
It need minor changes – but seems to work.
I did put in:
jQuery(document).ready(function() {…
In a tag just before the snippet:
Upload Image
Then Changed
function my_admin_scripts() {
wp_enqueue_script(‘media-upload’);
wp_enqueue_script(‘thickbox’);
wp_register_script(‘my-upload’, WP_PLUGIN_URL.’/my-script.js’, array(‘jquery’,'media-upload’,'thickbox’));
wp_enqueue_script(‘my-upload’);
}
function my_admin_styles() {
wp_enqueue_style(‘thickbox’);
}
if (isset($_GET['page']) && $_GET['page'] == ‘my_plugin_page’) {
add_action(‘admin_print_scripts’, ‘my_admin_scripts’);
add_action(‘admin_print_styles’, ‘my_admin_styles’);
}
to
function my_admin_scripts() {
wp_enqueue_script(‘media-upload’);
wp_enqueue_script(‘thickbox’);
}
function my_admin_styles() {
wp_enqueue_style(‘thickbox’);
}
add_action(‘admin_print_scripts’, ‘my_admin_scripts’);
add_action(‘admin_print_styles’, ‘my_admin_styles’);
Awesome, i learned a lot for your post and all the comments, thank you so much everyone. However i run into a problem. I would like to grab the ID of the attachment and save it in my field. Any idea how to do this?
Right now im using this:
var fileurl = jQuery(html).attr(‘href’);
So i can save the link of any file type not just the src of an image. It is not really pretty because, like one of the comment said, if the file link is set to NONE, it wont grab any info.
Im still a beginner so im a bit clueless as how to grab the attachment id when clicking “insert into post”. Does any one know how to? Is that information even there after i click “insert to post”?
Thanks in advance!
Hi there,
thanks for this tip. I am having trouble. I can open the upload window, I can upload an image, but when I click on the Insert Post button, the upload window disapeared but nothing happened. There is no URL inserted in the field. What am I missing? I am using WP 2.9.2. Thanks.
Hi guys,
It looks like (maybe with WP 3.0?) you need to pass the &page_id parameter in order for the “Insert” link to display.
So, you’d need to use this JS when invoking the page:
tb_show(”, ‘media-upload.php?type=image&post_id=1&TB_iframe=true’);
Thank you so much! Who would have thought I’d just have to add the 1…
I have upgraded to WP 3.0.1 and it started to work. But I have little problem. When I upload an image, then I press Insert to Post button, it insert to the field, but when I press Save button of the option page, the value from field dissapeares after refresh page. My other question is, how do I retrieve now the image to the theme template as for example a logo image. What value I should call.
I have the same question, have you solved this? thank you.
What if I wanted to allow them to upload something other than an image file? For example I have this working to a point and allow users to upload a GPX file. All I had to do was remove the ‘type=image’ from the tb_show and WordPress will handle what file types can be uploaded for me.
tb_show(”, ‘media-upload.php?type=image&TB_iframe=true’)
Launching the window and uploading the file is not the problem. It is getting the form text field to be populated with the GFX URL. I know I would have to change these lines….
imgurl = $(‘img’,html).attr(‘src’);
jQuery(‘#upload_image’).val(imgurl);
… to get them to look for something other than ‘img’ and ‘src’ But what?
Hi!
About insert into post.
And what happens, if you use this in your own page, where are no post id?
If i give a false post_id, it doesn’t works for me:
media-upload.php?type=image&TB_iframe=true&send=true&post_id=1
media-upload.php?type=image&TB_iframe=true&post_id=1
neither.
no error in console.
I’m having this issue too – the uploader aren’t on a page or post, so there’s no ID – and if the user has deleted the first post, then the Insert into Post button disappears.
Anyone?
Has anyone been able to get multiple media uploaders to work?? I’ve looked at the comments, but none of that code is working?
Yes, I do !
I managed to get as much field as I want with the “Insert into post” button but in a custom post type context.
Hey GREAT post. But have you got any advice on using this for more than one upload field?
Thanks again!
nevermind got a way for multiple fields thanks!
Care to share your code? It would be much appreciated : )
Hey Tom. I did but post was removed. I did however blog it here aswell http://www.janes.co.za.
i cant find it.
http://www.janes.co.za/use-the.....r-plug-in/
So in playing around with this, I noticed that it breaks the Featured Image function. Any idea what to change in the javascript so Featured Images work as they should?
Very useful, thanks. Combining this with a media_upload_tabs filter, you can hide tabs from the user as needed.
In the depths of your plugin/theme:
add_filter("media_upload_tabs", "my_media_upload_tabs_filter");
function my_media_upload_tabs_filter($tabs) {
if ("myvalue" === $_GET["mysetting"]) {
unset($tabs["type_url"];
}
return ($tabs);
}
And in your media uploader trigger:
tb_show('', 'media-upload.php?type=image&mysetting=myvalue&TB_iframe=true');
just a quick edit—missing closed paren
add_filter(“media_upload_tabs”, “my_media_upload_tabs_filter”);
function my_media_upload_tabs_filter($tabs) {
if (“myvalue” === $_GET["mysetting"]) {
unset($tabs["type_url"]);
}
return ($tabs);
}
Thanks for a great post.
Finally got things to work but I cant seem to find a solution for a way to grab the ID. Anyone out there who can give an example on how to pick it up (both in JS and PHP)?
I would owe you a beer!
Seb
This will work with multiple images and with WordPress 3.0+
win = window.win || window.dialogArguments || opener || parent || top;
win.$formfield = win.$formfield || null;
$(‘.upload_image_button’).click(function() {
win.$formfield = $(this).siblings(‘.upload_image_value’);
tb_show(”, ‘media-upload.php?type=image&hbgs_filter=media&TB_iframe=true’);
return false;
});
$(‘body’).ajaxSuccess(function(e, xhr, settings) {
if (settings.url == “async-upload.php”) {
$frag = $(“”+xhr.responseText+”");
if(win.$formfield && win.$formfield.size()) {
win.$formfield.val($frag.find(“.urlfile”).attr(“title”));
win.tb_remove();
}
}
});
Just been having a crack at this, and seems to work beautifully so far. Needs further testing though. Love the way that the bonus for using this method means that you can tap into the crop/rotate/flip image editing facilities, plus take advantage of the different thumbnail image sizes that get created every time you upload an image.
I also spent quite a bit of time trying to override the “Insert into Post” button text, as I am using this from my WordPress theme. I wanted something more intuitive such as “Insert into [theme name] Theme”. I finally did this via some (simple) jQuery magic and the ‘admin_head-media-upload-popup’ hook.
I will do a full walk-through post on my site, when I have time. Just contact me if you can’t wait until then!
Wow, great post. Succinct and straightforward. I need an upload feature in a plugin I’m building, and was getting ready to dig into the WordPress core files myself to see how this was done, then I figured I should give it a quick Google. Good job I did – probably saved myself at least 3 or 4 hours.
Would you know how to utilise the wordpress uploader without displaying the WP upload screen. I already have an upload function which is public on the site for visitors to upload images but I want to get wp to create different sized images for all the different post-thumbnails sizes I have set up. So that I can recall an image by using ‘the_post_thumbnail’ etc?
Anybody have any thoughts on how to get the width and height of the image pulled in too? I’ve got it working in all browsers except IE by replacing the ID’s and adding “width” and “height” in place “src” in the attr function. IE passes zero’s to the fields, but it works fine for the URL. I don’t really know what I’m doing with jquery. Any idea why this might be?
Here’s my full code:
jQuery(document).ready(function() {
jQuery(‘#upload_image_button’).click(function() {
formfield = jQuery(‘#logo_width’).attr(‘name’);
formfield = jQuery(‘#upload_logo’).attr(‘name’);
formfield = jQuery(‘#logo_height’).attr(‘name’);
tb_show(”, ‘media-upload.php?post_id=1&type=image&tab=library&TB_iframe=true’);
return false;
});
window.send_to_editor = function(html) {
jQuery(‘#logo_width’).val(jQuery(‘img’,html).attr(‘width’));
jQuery(‘#upload_logo’).val(jQuery(‘img’,html).attr(‘src’));
jQuery(‘#logo_height’).val(jQuery(‘img’,html).attr(‘height’));
tb_remove();
}
});
Insert into Post [FIXED]
A simple fix I use is to get the oldest post through PHP and use that to associate any uploads. You could do this with a page through a similar method.
PHP
global $post;
$fbposts = get_posts(‘order=ASC&numberposts=1′);
Then use this:
post_id=$fbposts[0]->ID
The issue is that the post_id has to exist. When an image is uploaded it’s associated with a post. The gallery is also automatically updated.
I hope this helps someone else as I spent a good couple hours sorting this out.
I try to use this for my admin page, but I don’t get the button to work at all.
Any ideas?
Where am I suppose to put all the different files?
great…i was searching for this kind of code, thanks
Hi Guys,
I am writing a free plugin to generate Facebook Fan Templates script, from the WordPress admin area, where you can upload a header, sheet background, social media icon, content background, logo or footer.
Add in text links and feeds then copy the html to your facebook page, which will link the images back to your wordpress uploads directory, that is free instead of having to use a pay service.
I have an array of upload buttons with the class=”upload_image_button”, each button has a unique name which has been set to the “id” of the textbox, then on-click store the name to set the value.
Saving the page will check the image attributes are within scope and copy the file to a folder.
I am new to javascript and have not been able to get a modified script to work.
When I press upload the system says working and the timer runs like it is loading but the upload screen is not showing.
So I think that the problem is with thick box show, maybe everything is not loading as it should:
tb_show(”, ‘media-upload.php?type=image&TB_iframe=true’);
Question = Is it the same process with a plugin that runs from the admin area, all I want is to upload and populate more than one textbox with an uploaded image url, this will then be moved to a folder.
Does anyone have a working plugin that uses several buttons and textboxes to share.
I can be contacted from my website if you have a sample.
Thanks in advance!
David
Revised file for the control array, edit timer keeps jumping:
http://digitalraindrops.pastebin.com/wqrWWGEp
I have it working now WordPress 3.0.3, with a few changes and Brians tip for the page id, in short while creating a plugin I had problems with the scripts not working, then I had debug errors because of the post id, and last it needed to work on a control array.
The Java Script:
This uses the click and gets two variables from the active [this] controls attributes name and title.
The parent button id and the post id, when you inset in post it populates the parent control, nice and simple uses the button name to associate the the textbox id.
http://digitalraindrops.pastebin.com/uLGAL4j6
This was how I registered the scripts, as it is loacal host and a plugin folder it was not working.
The admin PHP:
http://digitalraindrops.pastebin.com/Asr4F6PV
This is the control array, the buttons all have the same class name, but the name is unique and the id of the textbox, and the title uses a variable sat from Brians code as the last post id.
The controls array:
http://digitalraindrops.pastebin.com/DPvVXJRu
If anyone finds a way without adding to the posts gallery, please let us know.
I am using this for a free plugin, Facebook fan pages using the assets from your WordPress website, I will post back when it is in beta!
Thanks for all the posts, using bits and pieces worked in the end, so the few lines of code above may save some pain for others.
David
Solved: Nothing returned to text box.
So, like a lot of people in these comments, I ran into a really confusing issue where everything seemed to work except no value was returned by the upload tool.
After some debugging, and thanks to some info from other comments, I realized that the script worked fine _if_ I included a link with the image. Otherwise, jQuery( ‘img’, html) was empty.
So the problem is that the send_to_editor will pass _either_ an anchor element with a nested image element _or_ just the image element. How jQuery parses the returned object needs to depend on what type of element is returned.
I changed the send_to_editor to the example below and everything works perfectly:
window.send_to_editor = function(html) {
if ( jQuery(html).is("a") ) {
var imgurl = jQuery('img', html).attr('src');
} else if ( jQuery(html).is("img") ) {
var imgurl = jQuery(html).attr('src');
}
jQuery('#upload_image').val(imgurl);
tb_remove();
}
Otherwise, thanks for the great post, Matt!
PS- Maybe you could update your post so people don’t have to dig through the comments to figure this out.
How to get the image’s URL and attachment ID:
So I ended up also needing to use a custom metabox to manipulate the post’s feature image, which requires not only updating the ‘thumb’ meta data with the image’s URL, but also updating ‘_thumbnail_id’ with the correct attachment post’s ID.
Doing that is a little problematic, since I couldn’t find an easy way to get the ID from the URL itself. Fortunately, the value passed to send_to_editor contains a class attribute that includes ‘wp-image-###’ where ### is the image’s ID. A little string manipulation is all it takes to get grab the ID.
Here’s the code:
jQuery('#feature_image_button').click(function() {
formfield = jQuery('#feature_image_src').attr('name');
send_to_editor_clone = window.send_to_editor;
window.send_to_editor = function(html) {
if ( jQuery(html).is("a") ) {
var imgurl = jQuery('img', html).attr('src');
var imgid = jQuery('img', html).attr('class');
imgid = imgid.slice( ( imgid.search(/wp-image-/) + 9 ), imgid.length );
} else if ( jQuery(html).is("img") ) {
var imgurl = jQuery(html).attr('src');
var imgid = jQuery(html).attr('class');
imgid = imgid.slice( ( imgid.search(/wp-image-/) + 9 ), imgid.length );
}
jQuery('#feature_image_id').val(imgid);
jQuery('#feature_image_src').val(imgurl);
jQuery('#feature_image').attr('src', imgurl);
tb_remove();
window.send_to_editor = send_to_editor_clone;
}
tb_show('', 'media-upload.php?post_id=ID; ?>&type=image&TB_iframe=true');
return false;
});
A better way to get the attachment ID would be to parse the img class and just extract the digits.
imgclass = jQuery(html).attr(“class”);
imgid = parseInt(imgclass.replace(/\D/g, ”), 10);
You save my day dude. Thanks for this helpful comment.
Thanks alot Dagan Henderson.
Hi there!
Really great post, it helped me alot, but i still have a question have you find anyway to pass the image uploaded into the the editor?
I thought I had it sorted, I have the script in a plugin, so it loads and I have set the post->ID, that is great and it returns it to the plugins text box.
I then copy the image path in the textbox to a new folder, great!
Problem:
Posts > Posts, Edit (existing) when you try to insert an image you can’t as the script is still running, and it thinks the post is the last one.
Any Idea’s?
David
Here will working on multiple upload. Tested on WP 3.1RC3
jQuery(document).ready(function () {
jQuery('#upload_favicon').click(function () {
formfield = jQuery('#favicon_data');
post_id = jQuery('#post_ID').val();
tb_show('', 'media-upload.php?post_id=' + post_id + '&type=image&TB_iframe=true');
return false;
});
window.send_to_editor = function (html) {
imgurl = jQuery('img', html).attr('src');
jQuery('#favicon_data').val(imgurl);
tb_remove();
}
jQuery('#upload_logo').click(function () {
formfield = jQuery('#logo_data');
post_id = jQuery('#post_ID').val();
window.send_to_editor = window.send_to_editor_clone;
tb_show('', 'media-upload.php?post_id=' + post_id + '&type=image&TB_iframe=true');
return false;
});
window.send_to_editor_clone = function (html) {
imgurl = jQuery('img', html).attr('src');
jQuery('#logo_data').val(imgurl);
tb_remove();
}
});
post_id is required thing to show the Insert into Post button. You can replace with 0
just clone the window.send_to_editor if you have more more more upload fields
Hope it helps
Great post and excellent comments – thanks to everyone, helped me a lot.
One further question:
I am currently implementing a new taxonomy-image plugin using the wp uploader as described here. Does anyone know how I can get it to return a thumbnail of the image uploaded?
I want to replicate the functionality of the WP3 ‘featured image’ feature which displays a thumbnail of the uploaded/associated image on the admin/edit screen after upload and attachment completes.
Thanks for any help/hints.
Hi Rob. Have you looked at this plug-in by @_mfields: http://wordpress.org/extend/pl.....omy-images. I just tried it out- there’s a couple bugs, but it seems to do what you want.
Thanks for this post, I am using the code in a Templating plugin, one of the things I wanted to do is upload new and copy libary images to a new folder.
WordPress uses the ‘uploads’ folder for assets, so that is a good place, in the Pastebin code example below I wanted to share the two bits of cde I am using to put the files where I want them.
http://digitalraindrops.pastebin.com/W3UqTLZU
David
Thank you for this post – works like a charm!
This was much easier than I thought it would be. Tried to reverse engineer the WordPress file uploader but it was a pain.
Great tutorial and worked the first time. We’ll start using this in all our themes now. Thanks!
Hi!
Thank you Dagan Henderson, i thought i was lost.
I tried everything, with this post ID thing, but i realized, the importation of link url. But after that, i stucked.
Somehow Matt _should_update_his_post_ , because all the people link this page, how to use the uploader.
the media uploader work. The part “nextgen gallery works too, with the format “thumb” but no with the format “full size”…
strange
I’m having this problem too. I’m trying to use the media uploader in my own plugin, but cannot get file paths for full sized images in the next gen gallery. Only the thumbnail returns a value.
I got a hard time trying to get the POST_ID of the newly generated img at run time(Since it generates a attachment post).
Got it by doing the following in the window.send_to_editor :
imgClass=jQuery(‘img’,html).attr(‘class’);
var postId=imgClass.substring(imgClass.lastIndexOf(‘wp-image-’)+9);
It is dirty and unstable but will do the work
This is great. Working for me. thanks saved a lot of time and effort.
I got it working well. but the issue I am having now is getting the information into the database. I see the file uploads okay but I cannot get the information out of the input box and into the database. I am using the new method for making my admin area like so
which means my form needs to be this
$options = get_option('about_options');
I have this working just fine for a text field. But If I change the id and the name to use the php information that it needs to use for the database, then the input field no longer carries the information.
well, it looks like some of the code didn’t come through. but maybe you can still advise?
I’m using your trick but how I can use this at user front page instead of plugin ? I used same code but it gives me error and doesn’t display the media upload box
” tb_show is not defined
tb_show(”, ‘media-upload.php?type=image&TB_iframe=true’);
“
the upload scripts are probably not in place if you try to use this somewhere else.
you would need to enqeue the script in your page before.
i made some changes to the code of @Chris
the function can now be used on any field.
hope this help anyone.
`
//<![CDATA[
jQuery(document).ready(function() {
var formfield = '';
jQuery('#upload_image_button_1').click(function() {
formfield = jQuery('#_sfr_xx_meta_01').attr('name'); // set this to the id field you want to populate with the url
tb_show('', 'media-upload.php?post_id=ID; ?>&type=image&TB_iframe=1');
return false;
});
// Store original function
window.original_send_to_editor = window.send_to_editor;
/**
* Override send_to_editor function from original script
* Writes URL into the textbox.
*
* Note: If header is not clicked, we use the original function.
*/
window.send_to_editor = function(html) {
if (formfield == '') {
window.original_send_to_editor(html);
} else {
fileurl = jQuery(html).attr('href');
if (typeof(fileurl)=="undefined") {
fileurl = jQuery('img',html).attr('src');
}
jQuery('#' + formfield).val(fileurl);
tb_remove();
formfield = '';
}
}
});
//]]>
`
Need to implement a jquery iframe file upload that returns the folder and the filename back to the for into a custom field text box! – has somebody an idea ? – Thank you!
Hi everyone,
I don’t know if I’m too late or not.
But here is version of multiple uploader that works for me.
I just change a bit of the original code.
1.) Change ‘id’ to ‘class’
2.) Use this Javascript
jQuery(document).ready(function() {
jQuery(‘.upload_image_button’).click(function() {
formfield = jQuery(this).prev(“.upload_image”);
tb_show(”, ‘media-upload.php?type=image&TB_iframe=true’);
window.send_to_editor = function(html) {
imgurl = jQuery(‘img’,html).attr(‘src’);
formfield.val(imgurl);
tb_remove();
}
return false;
});
});
Hope this works for you
sorry I missed this
1.) Change ‘id’ to ‘class’
class=”upload_image”
class=”upload_image_button”
in each input box
This was the only working solution I could find in the comments, and so simple too. Thanks!
This worked perfectly! thanks.
thanks a ton man
if you only use `imgurl = jQuery(‘img’,html).attr(‘src’);`, it might not work.
if the user wants to put a file other then a img, like a .doc or a .pdf, sent to editor will not send back a you can extract the src from but a . then you would have to extract the href.
just saying …
nice tutorial!
works perfect.
thanks!
This isn’t doing anything for me, it displays the input form and upload button, but you can click it all day long and nothing happens.
I did everything you have there and replace the my_plugin_page with ?post_type=theposttypesname and it is still not doing anything.
Same problem as Alan. I have followed all the steps ad I get nothing. I am trying to add the upload box to a plugin named Events Manager. So all i have changed is the my_plugin_page with ‘?page=wp-events2′ Nothing happens and it does not actually load the script. is there any more detailed info on where to paste the code. I pasted in the plugin page that is for the admin area. Thanks for your help.
where do you guys put the script.
i place it in the admin page of my plugin and it works perfecly.
Make sure you add your plugin folder when adding the script:
WP_PLUGIN_URL.’/pluginfolder/my-script.js
I just made a my-script.js file like it says and assumed you dropped it in my plugins folder. I also just have a metabox registered for a custom post type that I am using this for.
try to place it directly in your admin page code.
if it works, then your good to go.
i noticed that placing this scrit in a external files did not wokr in most cases ..
hope it helps.
I’m not sure what you mean by the admin page. Are you editing the raw WordPress files.
Great article! I’m currently using this to add a picture field to the User Profile page.
I have a weird issue with jQuery not being able to select the img src.
window.send_to_editor = function(html) {
console.log(html);
//outputs
imgurl = jQuery(‘img’,html).attr(‘src’);
//outputs undefined
console.log(imgurl);
jQuery(‘#upload_image’).val(imgurl);
tb_remove();
}
slecting the src directly on the html element works
imgurl = jQuery(html).attr(“src”);
but I know this is not the best solution.
I have a weird issue with jQuery not being able to select the img src.
window.send_to_editor = function(html) {
console.log(html);
//outputs (with tags omitted) img src=”url/glasses.jpg” alt=”" title=”glasses” width=”391″ height=”266″ class=”alignnone size-full wp-image-132″
imgurl = jQuery(‘img’,html).attr(‘src’);
//outputs undefined
console.log(imgurl);
jQuery(‘#upload_image’).val(imgurl);
tb_remove();
}
slecting the src directly on the html element works
imgurl = jQuery(html).attr(“src”);
but I know this is not the best solution.
Thanks fo this nice article.Can you please tell me how to upload video and image in the theme option page?
Hi! I’d welcome a suggestion to deal with jQuery(document).ready(function() {…}) never being called, as I have a page with so many jQuery-based elements that some must have called that before.
http://api.jquery.com/ready/ suggests to use jQuery(document).bind(“ready”, function() {…}) when .ready() has already been called, but this doesn’t work for me either.
I’m trying to use onclick on the button instead and will report if there is any progress.
Well well, what do you know… onclick on the button works flawlessly
Gosh, just to imagine I spent countless hours yesterday until late in the AM to get it working when it was so incredibly easy…
FYI,
…form…
… Javascript
function myMediaPopupHandler()
{
window.send_to_editor = function(html) {
imgurl = jQuery(‘img’,html).attr(‘src’);
jQuery(‘#upload_image’).val(imgurl);
tb_remove();
}
formfield = jQuery(‘#upload_image’).attr(‘name’);
tb_show(”, ‘media-upload.php?type=image&tab=library&TB_iframe=true’);
return false;
}
In my case, I need to add before media-upload.php; I’m using this on a plugin; that tiny JavaScript snippet is actually inline in the header and not loaded from a separate file.
… grr, wp-ajax-edit-comments ate up my PHP code… lol. You should consider getting rid of that old (and paid!) plugin and use IntenseDebate from Automattic or Disqus; I’ve used both on my many blogs, and both provide a much superior interface than wp-ajax-edit-comments (which I had also used before).
I can’t even delete/edit comments on Google Chrome; my guess is that wp-ajax-edit-comments, since it predates Google Chrome, does some incompatible things that simply don’t work.
Anyway… enough ranting about wp-ajax-edit-comments… back to the issue:
…form…
<input id=”upload_image” name=”upload_image” type=”text” />
<input id=”upload_image_button” value=”Get image” type=”button” onclick=”myMediaPopupHandler();” />
… Javascript
function myMediaPopupHandler()
{
window.send_to_editor = function(html) {
imgurl = jQuery(‘img’,html).attr(‘src’);
jQuery(‘#upload_image’).val(imgurl);
tb_remove();
}
formfield = jQuery(‘#upload_image’).attr(‘name’);
tb_show(”, ‘media-upload.php?type=image&tab=library&TB_iframe=true’);
return false;
}
In my case, I need to add <?php echo admin_url(); ?> before media-upload.php; I’m using this on a plugin; that tiny JavaScript snippet is actually inline in the header and not loaded from a separate file (it seemed overkill to me to insist putting it on an external file).
Hi all,
I made lots of testing and grab bit and pieces from all the comments and here is my SOLUTION for multiple uploader with only using Class not ID.
// Image 1 Handler
jQuery(document).ready(function() {
jQuery(‘.upload_image_button’).click(function() {
formfield = jQuery(this).prev(‘.upload_image’);
tb_show(”, ‘media-upload.php?type=image&TB_iframe=true’);
window.send_to_editor = function(html) {
if (jQuery(html).is(“a”)) {
var imgurl = jQuery(‘img’, html).attr(‘src’);
} else if (jQuery(html).is(“img”)) {
var imgurl = jQuery(html).attr(‘src’);
}
jQuery(‘.upload_image’).val(imgurl);
tb_remove();
}
return false;
});
// Image 2 Handler
jQuery(‘.upload_image_button2′).click(function() {
formfield = jQuery(this).prev(‘.upload_image2′);
tb_show(”, ‘media-upload.php?type=image&TB_iframe=true’);
window.send_to_editor = function(html) {
if (jQuery(html).is(“a”)) {
var imgurl = jQuery(‘img’, html).attr(‘src’);
} else if (jQuery(html).is(“img”)) {
var imgurl = jQuery(html).attr(‘src’);
}
jQuery(‘.upload_image2′).val(imgurl);
tb_remove();
}
return false;
});
});
Image 1
Image 2
I hope this help you all
Thanks.
Hi all. I feel I’ve found the right place to as my question. I want to insert a button in the visual text editor that pops up a box which populates three drop down list boxes with the video files that have been uploaded to the current article (or most recent videos uploaded). I’ll process this along with other inputs added in the form to create a shortcode which is inserted into the post. So far I think I’ve found how to add a button image to the text editor alongside the Upload/Insert (Add Media) button image.
Would love help with getting the video list and the “insert into post” segments.
Thanks.
Man, where i add this u code? which file.php i need edit for post area?
hi all
The javascript given here is only part of the solution.
I usaly place this script inline in the admin page of the plugin i’m developing.
This is the function i’m using:
var formfield = ”;
jQuery(document).ready(function() {
// Store original function
var original_send_to_editor = window.send_to_editor;
/**
* Override send_to_editor function from original script
* Writes URL into the textbox.
*
* Note: If header is not clicked, we use the original function.
*/
window.send_to_editor = function(html) {
if (formfield == ”) {
original_send_to_editor(html);
} else {
fileurl = jQuery(html).attr(‘href’);
if (typeof(fileurl)===”undefined”) {
fileurl = jQuery(‘img’,html).attr(‘src’);
}
jQuery(‘#’ + formfield).val(fileurl);
tb_remove();
formfield = ”;
}
}
});
/*—————————-*/
// field 1
jQuery(‘#_sfr_name_of_your_meta_value1_btn’).click(function() {
formfield = jQuery(‘#_sfr_name_of_your_meta_value1′).attr(‘name’); // set this to the id field you want to populate with the url
tb_show(”, ‘media-upload.php?post_id=3728&type=image&TB_iframe=1′);
return false;
});
// field 2
jQuery(‘#_sfr_name_of_your_meta_value2_btn’).click(function() {
formfield = jQuery(‘#_sfr_name_of_your_meta_value2′).attr(‘name’); // set this to the id field you want to populate with the url
tb_show(”, ‘media-upload.php?post_id=3728&type=image&TB_iframe=1′);
return false;
});
I made a class so you can easily add this feature to any custom field.
http://snippet.9ieme.com/2011/.....t-a-plugin
If you don’t know where to place this code, maybe you should try it out.
Hope it help anyone
Have fun !
Thank you very much!
Thank so much to all..
how i get the image uploaded in my index.php.
Normally for a custom type i put this code where i want see custom type..
ID, “Before”, $single = true) != “”) :
echo get_post_meta($post->ID, “Before”, $single = true);
endif;
?>
this is correct?
this is the code…sorry
if(get_post_meta($post->ID, “Before”, $single = true) != “”) :
echo get_post_meta($post->ID, “Before”, $single = true);
endif;
?>
this is correct?
Maybe you should try and see if custom filed has the proper name.
Try this, it should help you see if your value is set and what name it has …
$custom = get_post_custom( $post->ID );
print_r( $custom );
I would like only display on front end the image that i have attached on admin panel with the Matt function .
Dear wise mans. There must be a solution for this.
I am using two meta boxes for custom post type “products”.
First consists of two metafields what is for adding two addition product pictures
The second one is for creating a simple gallery for this product.
Each of them has their own tb_show and window.send_to_editor stuff.
The thing is that everything works fine when there are registered only one metabox – the first or the second. If there are registered both of them, the last registered via add_meta_box , brings the error in firebug “too much recursion” when pressing “Insert into post” button.
How to solve this?
hey Janis.
I must have spent 3 hours the other day trying to solve this.
This problem occurs when you try to use the original send_to_editor function.
It just called itself for ever.
Try not declaring multiple function send_to_editor.
here is the code i use:
var formfield = ”;
var original_send_to_editor = window.send_to_editor;
/**
* Override send_to_editor function from original script
* Writes URL into the textbox.
*
* Note: If header is not clicked, we use the original function.
*/
window.send_to_editor = function(html) {
if (formfield == ”) {
original_send_to_editor(html);
} else {
fileurl = jQuery(html).attr(‘href’);
if (typeof(fileurl)===”undefined”) {
fileurl = jQuery(‘img’,html).attr(‘src’);
}
jQuery(‘#’ + formfield).val(fileurl);
tb_remove();
formfield = ”;
}
}
Hope it helps.
I tested the code in this class i made and i got this problem solved.
the code is here:
http://snippet.9ieme.com/2011/.....t-a-plugin
There must be something wrong in the js script or function codes.
Is there anyone who got it work?
The solution that solved my problem! http://wordpress.stackexchange.....-different
For custom post types, the following code will hijack the Insert into Post button and insert the value into an input field instead. Make sure your custom post type supports ‘editor’.
jQuery(document).ready(function(){
window.original_send_to_editor = window.send_to_editor;
window.send_to_input = function(html){
imgurl = jQuery(‘img’, html).attr(‘src’);
jQuery(‘#img_input_field’).val(imgurl);
tb_remove();
}
jQuery(“.button_for_img_input_field”).click(function(){
window.send_to_editor = window.send_to_input;
});
jQuery(“#add_image”).click(function(){
window.send_to_editor = window.original_send_to_editor;
});
});
If you don’t want to display the editor you’ll have to hide it using jQuery in this code or enqueueing an additional stylesheet:
#postdivrich{display: none}
Hopefully next WordPress releases will allow for a better break down of post type support, like having ‘media-upload’ and ‘file-upload’ next to ‘editor’.
If you’re using this in a custom post type and want the upload to be attached to the post, then you just need to edit the JavaScript to say:
tb_show(”, ‘media-upload.php?type=image&post_id=’+ jQuery(‘#post_ID’).val() +’&TB_iframe=true’);
The comment from Syaiful Shah Zinan worked perfectly for getting multiple uploaders on the same page.
Thanks for the post, Matt!
Matt,
I don’t know if you could help me. I like the way this works. What about audio? Would somebody be able to show me how you use jQuery to get the audio file, say MP3. I want to do something like this, but this doesn’t work.
…
…
…
window.send_to_editor = function(html) {
audioURL = jQuery(‘audio’,html).attr(‘src’);
jQuery(‘#upload_audio’).val(audioURL);
tb_remove();
}
…
Frank T,
its a few posts up from yours question
window.send_to_editor = function(html) {
url = jQuery(html).attr(‘href’);
jQuery(‘#upload_audio’).val(url);
tb_remove();
}
This is my complete script for media uploader. I hope this can be helpful.
jQuery(document).ready(function() {
// Browse MP3
jQuery(‘#upload_mp3_button’).click(function() {
formfield = jQuery(‘#upload_mp3′).attr(‘name’);
tb_show(”, ‘media-upload.php?type=audio&tab=library&TB_iframe=true’);
return false;
});
// Input MP3
window.send_to_editor = function(html) {
url = jQuery(html).attr(‘href’);
// Get File Extension
var filext = url.substring(url.lastIndexOf(“.”)+1);
// Checking Extension
if(filext != “mp3″){
alert(“Invalid File Format Selected”);
tb_remove();
}else {
jQuery(‘#upload_mp3′).val(url);
tb_remove();
}
}
});
Como utilizo
if (isset($_GET['page']) && $_GET['page'] == ‘my_plugin_page’)
No puedo insertar imagenes en post?
Alguna idea porque pase esto
Hi,
I’ve written a simple widget plugin for a jquery slideshow which is working fine but i want to have the upload image available from the widget admin area. However when i add this code nothing happens when the button is clicked. I can see that my-upload script is loading on the page though as i removed the if statement for now.
I can access the image uploader using as link:
<a onclick="return false;" title="Upload image" class="thickbox" id="add_image" href="/wp-admin/media-upload.php?type=image&TB_iframe=true&width=640&height=105″>Upload Image
but then can’t seem to return the URL to the text field?
Any suggestions as i can’t seem to find anyone else using an image uploader for a widget, is it even possible?…
all the JS script in place for the media uploader might not be loaded on the widget admin page.
i would compare what script are loaded on a post edit pad and load the missing script in the widget admin page.
Hi Ralph,
I know it has been a while since you posted this question. I am just curious if you, or anyone else, ever figured out a solution to this problem. Thanks!
Hi, I’m trying to use your solution combined with a tutorial that I found on NetTuts,
almost everything is working properly there is only 1 BIG bug…
After uploading the image I can see her URL but as soon as I save the option page it reloads and the form become empty then if I try to echo the fuction I oly have empyspace… any Idea?
Here is my pastebin:
http://pastebin.com/rczcaCD3
Thank you very mmuch!
I cannot get this to work at all, the button is dead, if i hover over it there is an effect but clicking does nothing. I have loaded the functions at the top of my page template, created the js file and mirrored the html portion exactly and still no dice. Am I missing something?
I fixed it, I had to comment out the if statement. Im still learning so could someone let me know what the purpose of the if statement was?
Thanks,
Thank you! This worked really well. In 3.2.1 I had to use the plugins_url() function in order for it to find the correct location of my javascript file. Other than that, works really nicely and so much easier for users.
You can even use this :
wp_register_script(‘my-upload’, get_bloginfo(‘template_url’).’/my-script.js’, array(‘jquery’,'media-upload’,'thickbox’));
You just have to place the my-script.js file inside your theme folder, and you can call it by the above code.
I’m trying to use this code to include an image upload function in a plugin I’m modifying. I managed to get the media upload box to start when I press the button. I can upload the image from there but when I press the insert into post button the inside of media upload window becomes blank and it doesn’t close.
Does this happen to anyone else?
When I close the window manually pressing the x on the top right corner I can see that the text box hasn’t been filled with the link to the image.
Thanks for posting this code anyway though.
This is a common problem.
Do you have any javascrit error that fire in firebug / safari inspector ?
i Bet you do.
That problem is probably because the function calls it’s self in a endless loop.
Let me know if you have JS error.
Actually I do. I get a “edCanvas not defined” error. Thanks to google I found out that it is related to tinyMCE but I couldn’t find any clear solution
Hey I just used this to make plugin to upload image from front end but
media upload and thickbox js are not loading result its not working for me, could you please guide me to overcome from this issue
Thank you so much. Just what I was looking for! Excellent!
how can i change the upload directory please ?
The upload dir is the same as the regular upload dir.
I believe you can change it in the WP media option page (wp-admin/options-media.php)
if you want to use a different did then the one set in the options, then it’s much more complicated as this technique use the original WP upload functions.
Ok thanx !
Hello there,
As I’m using this solution (thanks for it) in a plugin I’m working on and read that some people have some issues I’ve to deal with as well here is how I’ve change the code.
Using jQuery core function in a context works like the .find() method and start the search of the element from the first one. Depending on you define a target url or not the HTML contains at first a A markup or directly the IMG one. In this last case the code at the top won’t work. So just first create a DIV element and put the hole html into:
// Overrides the send_to_editor() function in the media-upload script window.send_to_editor = function(h) { // Put the html into a holder div so .find() method or using a context works in every cases (link or not) h = jQuery(document.createElement('div')).html(h); // Get our attributes from the html var imgSrc = jQuery('img',h).attr('src'); var imgAlt = jQuery('img',h).attr('alt'); var imgWidth = jQuery('img',h).attr('width'); var imgHeight = jQuery('img',h).attr('height'); var imgClass = jQuery('img',h).attr('class'); // May return undefined if there's not link var aHref = jQuery('a',h).attr('href'); }Does not work with WordPress 3.3?
It works for WordPress 3.3 Mr. X .
I tried it.
Hello, Thanks for provide the easy way to add editor in Custom plugin. But We have some error to upload Image, Audio, video.
As we click to media upload at the top left, it is not pop up on the same page,redirected on another window.
Please help me how can i fix this .
Is there a way to get the Link-Browser to get the URLs of existing Pages? It works great for images in the Library but I also need to link pages and articles…
Any idea how to save the user from clicking “insert into post” and have the function send_to_editor be called automatically once the file is uploaded?
Cool This code is working, you are awesome. Cheers Matt
Wonderful buddy. Keep it up. (y)
Hi! I’ve been reading your weblog for a long time now and finally got the courage to go ahead and give you a shout out from Huffman Texas! Just wanted to say keep up the excellent work!
“Any idea how to save the user from clicking “insert into post” and have the function send_to_editor be called automatically once the file is uploaded?”
I am looking for same information too, i am not programming professional, any idea, please?
its so impressive i will use it in future for my site
Thanks,man
Thanks you. Exactly what I was looking for.
Is there a way to pass the image url back to the admin page?
Hi,
This one is a very useful post, very well explained.
I’ve been searching this for months.
You made things better. Thanks for saving my day.
Some could just help me telling me where i have to paste the second and third code?
This is a good tutorial but still i want user to upload files without logging in to the site. media-upload.php doesnt allow this.
Can anybody please provide me some help on that.
Thanks in Advance for lokking an dreading this
thanks it’s very useful…
The only solution worked for me Beutifully after trying tons of solutions :
my-script.js
——————————————————–
jQuery(document).ready(function() {
jQuery(‘.upload_image_button’).click(function(){
formfield = jQuery(this).prev(“.upload_image”);
tb_show(”, ‘media-upload.php?type=image&TB_iframe=true’);
return false;
});
window.send_to_editor = function(html) {
imgurl = jQuery(‘img’,html).attr(‘src’);
formfield.val(imgurl);
tb_remove();
}
});
HTML
————————————————–
Upload Image
<img width="170" height="80" src="” />
Upload Image
<img width="170" height="80" src="” />
Sorry HTML truncated in last post, here it is
Upload Image
<img width="170" height="80" src="” />
Do you mind to post the solution again?
Maybe you can escape the code before paste it here (check this online escape tool http://www.htmlescape.net/htmlescape_tool.html )
and then poste the code
Thanks in advance
Hi Daniel,
Here is the HTML
————————————–
<tr valign="top"> <th scope="row">Upload Image</th> <td> <label> <input class="upload_image" type="text" size="36" name="mytheme_theme_options[image1]" value="" /> <input class="upload_image_button" type="button" value="Upload Image" /> </label> <img width="170" height="80" src="<?php echo ($options['image1']); ?>" /> </td></tr><tr valign="top"> <th scope="row">Upload Image</th> <td> <label> <input class="upload_image" type="text" size="36" name="mytheme_theme_options[image2]" value="" /> <input class="upload_image_button" type="button" value="Upload Image" /> </label> <img width="170" height="80" src="<?php echo ($options['image1']); ?>" /> </td></tr>
———————————————–
And here the Javascript again
———————————————–
jQuery(document).ready(function() {
jQuery(‘.upload_image_button’).click(function(){
formfield = jQuery(this).prev(“.upload_image”);
tb_show(”, ‘media-upload.php?type=image&TB_iframe=true’);
return false;
});
window.send_to_editor = function(html) {
imgurl = jQuery(‘img’,html).attr(‘src’);
formfield.val(imgurl);
tb_remove();
}
});
——————————————————
How would i change the Js to allow multiple upload fields on the same admin page?
Here is a article to add multiple image upload buttons. Click here
Hey, i wrote something about the wordpress uploader (with drag and drop ajax functionality you can check it out : http://bit.ly/H5KJYt )
I tried this and it didn’t work, then i tried Cedric’s solution from above, copy-paste and in 5 mins I had a working image uploader plugin. I tried to leave a comment on cedric’s site but it was asking to login. Just wanted to say a BIG thank you….truly brilliant work!
nice post, gonna try to implement image upload
Hi i have implemented this codes in a new theme i am developing in wordpress gantry framework, the thing is that all works perfectly and also i get the image url in my input box when i click in the button, insert into post.
The only thing i need know is to include this image url in my css as a variable in a style declaration php file that goes as follow:
$css .= ‘#rt-logo {background-image: url() 0 0 no repeat;}’;
where this $logoimage is the img url, but i don´t know which variable to call to make it work , i have probed with imgurl and it doesn´t work.
Help would be appreciated and perhaps someone is trying to do this…
Thank you and sorry for my english, i am spanish from La Manga del Mar Menor
Sorry the css has an error, it goes like follow:
$css .= ‘#rt-logo {background-image: url() 0 0 no repeat;}’;
where this $logoimage is the img url, but i don´t know which variable to call to make it work , i have probed with imgurl and it doesn´t work.
Help would be appreciated and perhaps someone is trying to do this…
Sorry it doesn´t let me write the php code to call variable that goes inside the url(), but you can imagine, what i need to know is which variable to call or how to save it as a variable and then call it from css.
Thank you
Thank you so much
Hi Matt, I’d just like to insert a shortcode generated in a pop-up window into the editor. I generate the shortcodes from media attachment urls and other form inputs. Right now I echo the shortcode into a textarea and copy-paste it into the post. I’d like to insert the shortcode [video mp4="http://pathto-file height="480" etc] into the post and close the window.
Could you point me in the right direction?
Thanks.
Totally having trouble with this. I click the upload button and nothing happens. Can anyone help? I will post code if necessary.
No, it’s not necessary to post code. People should be able to guess what’s wrong.
AWESOME!!! Thanks
I spent quite a few hours trying to figure out how to get an image uploader into my custom backend admin page, and I kept finding things that ended up being slightly different, or written for WordPress 2.x, or just flat out didn’t work. Thank you for the help!
I’d like to point out though that the table structure you have isn’t necessary if one is using the Settings API, I just stripped everything down to the label, and even got rid of that in the end.
So great with me.Thanks so much.
Anyone ever used the code inside functions.php of a theme?? because I failed doing so.
If you have more than 1 input area like Logo and Background-Image
You should do this;
HTML inputs
Logo
Bg Image
//different ID
JAVASCRIPT
Firstly change the formfield line in the javascript. to
formfield = jQuery(this).prev(‘input’);
// it was given input name.
So it should look like that
jQuery(document).ready(function() {
jQuery(‘#upload_image_button’).click(function() {
formfield = jQuery(this).prev(‘input’); // we changed here
tb_show(”, ‘media-upload.php?type=image&TB_iframe=true’);
return false;
});
jQuery(‘#upload_image_buttonBG’).click(function() { // id for bg button
formfield = jQuery(this).prev(‘input’);
tb_show(”, ‘media-upload.php?type=image&TB_iframe=true’);
return false;
});
// fixed function.
window.send_to_editor = function(html) {
imgurl = jQuery(‘img’,html).attr(‘src’);
jQuery(formfield).val(imgurl);
tb_remove();
}
});
We have two function for buttons (you can add more) and one function for sending it to the field
Even if you add more, the last function is fixed, just add more button functions.
Cheers.
Really wonderful and nice help . Thanks a lot for such documentation .
Thank you
Great stuff!
But i got a bug. When the “Insert to Post” is triggered you can’t add images to the original post, they will appear where you told it to appear.
I fixed it by make this restoring code after the tb_remove();
window.send_to_editor = function(c)
{
var b,a=typeof(tinymce)!=”undefined”,f=typeof(QTags)!=”undefined”;if(!wpActiveEditor){if(a&&tinymce.activeEditor){b=tinymce.activeEditor;wpActiveEditor=b.id}else{if(!f){return false}}}else{if(a){if(tinymce.activeEditor&&(tinymce.activeEditor.id==”mce_fullscreen”||tinymce.activeEditor.id==”wp_mce_fullscreen”)){b=tinymce.activeEditor}else{b=tinymce.get(wpActiveEditor)}}}if(b&&!b.isHidden()){if(tinymce.isIE&&b.windowManager.insertimagebookmark){b.selection.moveToBookmark(b.windowManager.insertimagebookmark)}if(c.indexOf(“[caption”)===0){if(b.wpSetImgCaption){c=b.wpSetImgCaption(c)}}else{if(c.indexOf(“[gallery”)===0){if(b.plugins.wpgallery){c=b.plugins.wpgallery._do_gallery(c)}}else{if(c.indexOf(“[embed”)===0){if(b.plugins.wordpress){c=b.plugins.wordpress._setEmbed(c)}}}}b.execCommand(“mceInsertContent”,false,c)}else{if(f){QTags.insertContent(c)}else{document.getElementById(wpActiveEditor).value+=c}}try{tb_remove()}catch(d){}
}
I guess there’s a better way to fix this bug?
Great tip, thanks mate.
There’s only one thing, you can skip the last conditional:
if (isset($_GET['page']) && $_GET['page'] == ‘my_plugin_page’)
Just by simply adding the plugin page name to the action hook after a “-”
add_action(‘admin_print_scripts’.'-my_plugin_name, ‘my_admin_scripts’);
add_action(‘admin_print_styles’.'-my_plugin_name, ‘my_admin_styles’);
Best regards,
CoolArts.
Nice article thanks i’m searching for it for my theme options page
Thank you very much.. It really helps
That Was Helpful Tnx
Hey there! This is my first visit to your blog! We are a team
of volunteers and starting a new initiative in a community in
the same niche. Your blog provided us useful information to work on.
You have done a extraordinary job!
I really like your blog.. very nice colors & theme.
Did you make this website yourself or did you hire someone to do it for
you? Plz respond as I’m looking to construct my own blog and would like to know where u got this from. thanks a lot
It’s remarkable to pay a visit this web page and reading the views of all mates concerning this paragraph, while I am also keen of getting experience.
When I originally commented I seem to have clicked on the -Notify me when new comments are added- checkbox and from now on every time a comment is added I get 4 emails with the same comment. Perhaps there is a means you can remove me from that service? Many thanks!
everything is working perfect for me, except all of images in media library appear unattached to posts. what do I do?
Thanks! This was quite helpful.
After uploading the image and adding it to my plugin page, I wanted it to return the image ID and show a thumbnail. Here’s the code for it: http://www.darrenkrape.com/use.....ur-plugin/
Gist sample: https://gist.github.com/benallfree/5282099
I think this one could be helpful:
http://wordpress.org/extend/plugins/uploadcare/
conflict button “Add media” . I used insert into post in “Add media” but it’s not work
wordpress 3.5.1
Hmm is anyone else experiencing problems with the pictures on
this blog loading? I’m trying to figure out if its a problem on my end or if it’s the
blog. Any feedback would be greatly appreciated.