I was recently working on a wordpress plugin and need a very small image upload feature just to upload company logo. I was thinking to use the original wordpress file uploader, as it is really very cool and easy to use as well. So after checking few code snipped’s I found the below solution:
Here is the html code for browse button,
<input id="company_logo" type="text" name="company_logo" size="36" /> <input id="upload_button" type="button" value="Upload Image" />
You are required to add these javascript libraries to achieve the lightbox effect and uploader screen
add_action('init', 'call_init');
function call_init()
{
wp_enqueue_script("jquery");
wp_enqueue_script('media-upload');
wp_enqueue_script('thickbox');
wp_enqueue_style('thickbox');
}
and now the actual javascript code, which will do the magic
jQuery('#upload_image_button').click(function() {
formfield = jQuery('#company_logo').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('#company_logo').val(imgurl);
tb_remove();
}
Above code will open a thikbox and allow user to upload image or select from the uploaded one like one we can while adding thumnails or post images on post page. Once image gets uploaded and user presses “insert into post”, the “send to editor” function gets activated and it will copy the image url to input box you had created in the html.
This will look exactly like wordpress image uploader screen.
So upload functionality done here, but what I required was to get the image id or say attachment id once image uploaded successfully and url comes in input box, and for that there is a hook in the wordpress api which we can use while user click “insert into post” button, it is “image_send_to_editor”
add_filter('image_send_to_editor', 'image_to_editor', 20, 8);
“image_send_to_editor” hook get’s called in the background when user press ‘insert into post’ button and provides various parameter, like html, attachment id, caption of the image, title of the image, alignment of the image, url, size and alt tag of the image.
As I only need attachment id from that function to save in db and latter can use it for thumbnail generation, so I just updated a option in the database to save it.
function image_to_editor($html, $id, $caption, $title, $align, $url, $size, $alt)
{
update_option('company_logo_id', $id);
return $html;
}
Hope this will help in image upload features of wordpress plugins. Feedback and questions are welcome here.



