Ralph Logan
Ralph Logan

Reputation: 21

Wordpress Custom Image Upload Field

I am currently developing a WordPress site which needs a custom content add/edit module. I am looking for an image upload option in wordpress, for eg. in my form there is an input field titled 'Choose Image', when the user clicks on the input field, i want the wordpress media gallery to popup and be able to choose an image from the gallery. and once the user selects an image, the full url to the image will be filled in the input field. I am sure this can be done because i have once found a code for this, but i forgot where i found it. Please help everybody

Thanks in Advance..

Upvotes: 2

Views: 4965

Answers (1)

JB McKee Bowers
JB McKee Bowers

Reputation: 81

Here is code that will do this:

jQuery(document).ready(function() {

    var orig_send_to_editor = window.send_to_editor;

    jQuery('#upload_image_button').click(function() {
        formfield = jQuery(this).prev('input');
        tb_show('', 'media-upload.php?type=image&TB_iframe=true');

        window.send_to_editor = function(html) {
        var regex = /src="(.+?)"/;
        var rslt =html.match(regex);
        var imgurl = rslt[1];
        formfield.val(imgurl);
        tb_remove();
        jQuery('#show_'+formfield.attr('name')).html('<img src="'+imgurl+'" width="" />')

        window.send_to_editor = orig_send_to_editor;
    }

    return false;
});
});

Here is the HTML to go with it:

<input type="hidden" name="upload_image" />
<?php $post_img = get_post_meta($post->ID,'item_image',true); ?>
<input id="upload_image_button" type="button" value="<?php echo (empty($post_img)?'Upload Image':'Change Image') ?>" />
<div id="show_upload_image"><?php echo (!empty($post_img)?"<img src='$post_img' width='100' />":'')?></div>

Upvotes: 3

Related Questions