Blog

Using the Worpress Media Uploader With Custom Fields

WordPress custom fields are useful for customizing posts and pages, but they should be limited to text-based properties .  Many theme developers provide custom fields for images and require their users to enter the URL of the image.  Though effective, this is very unusable and a burden for non-technical users. Finding the correct url and then copying and pasting it into the field is cumbersome and error prone and most users can not be expected to do this properly or have the technical know how.

A much more usable solution is to integrate the WordPress Uploader and allow the user to upload and select files from the media library just like inserting images into a post.  With a small amount of code, this is easily done.

To display the uploader, you need to call the following javascript function.

tb_show('', 'media-upload.php?TB_iframe=true');

After the user uploads and/or selects a file and clicks “Insert into Post”, the uploader calls another function, window.send_to_editor(html) and passes in an HTML snippet consisting of an anchor tag linking to the file. We simply need to override this function and extract the url of the file. We can then insert the url anywere we want. Typically, you’d want to insert the url into a form field that will be saved as meta data with the post or page.

jQuery('.image_upload_button').click(function() {
    tb_show('', 'media-upload.php?TB_iframe=true');
    window.send_to_editor = function(html) {
        url = jQuery(html).attr('href');
        jQuery('#myInputField').val(url);
        tb_remove();
    };
    return false;
});

An easy way to include this Javascript is to embed it in the header of the post or page editor. However, it’s better to create a separate Javascript file and put your code in there. Both methods are shown below.

Embed Javascript in Header

function embedUploaderCode() {
?>
    <script type="text/javascript">
    jQuery(document).ready(function() {
        jQuery('.image_upload_button').click(function() {
            tb_show('', 'media-upload.php?TB_iframe=true');
            window.send_to_editor = function(html) {
                url = jQuery(html).attr('href');
                jQuery('#myInputField').val(url);
                tb_remove();
            };
        return false;
        });
    });
    </script>
<?php 
}
add_action('admin_head', 'embedUploaderCode');

Include External Javascript File

function my_admin_scripts() {
?>
    <script type="text/javascript" 
            src="<?php bloginfo('template_directory'); ?>/lib/MyAdminCode.js">
    </script>
<?php 
}
add_action('admin_head', 'my_admin_scripts');

If you want to add the image uploader on a page that doesn’t have an editor, you’ll need to tell WordPress to load the required javascript and css for the uploader. This is easily done in functions.php with the code below.

function loadUploaderScripts () {
    wp_enqueue_script('media-upload');
    wp_enqueue_script('thickbox');
}
add_action('admin_print_scripts', 'loadUploaderScripts');
 
function loadUploaderStyles() {
    wp_enqueue_style('thickbox');
}
add_action('admin_print_styles', 'loadUploaderStyles');

My next post will show how to create custom meta boxes that use the image uploader. So keep checking back or subscribe to my RSS Feed to be notified when the article is posted. Also, let me know if you have any problems getting this to work by leaving a comment below.

6 Responses

  1. 1
    burntdownhouse

    Thanks, looks promising. When can we expect part 2?

  2. 2

    Thanks for pulling together this code, I went through about 6 examples people have created to show how to insert images, but not files too. Your code is also much more concise, great job!

  3. 3

    Hi , good tutorial but i think you have an error.
    When your js run the window.send_to_editor property is set to your new function and update your custom field. This is ok but what happen if you click on the standard media button above the text editor ? Media will no sent to editor because “send_to_editor” point to your custom field.
    So here the solution:
    jQuery(document).ready(function() {

    var my_original_editor = window.send_to_editor;

    jQuery(‘#upload_image_button’).click(function() {
    formfield = jQuery(‘#mp_preview_image’).attr(‘name’);
    tb_show(”, ‘media-upload.php?type=image&TB_iframe=true’);

    window.send_to_editor = function(html) {
    imgurl = jQuery(‘img’,html).attr(‘src’);
    jQuery(‘#mp_preview_image’).val(imgurl);
    tb_remove();
    window.send_to_editor = my_original_editor;
    }
    return false;
    });

    });

  4. 4

    Thanks for sharing, great code and with the comment of Luigi also compatible with media upload button for the content!

  5. 5

    This was so much more helpful than any other tutorial I’ve read. Thank you for sharing! Now, hopefully I can get my media upload button to finally work. Just having troubles saving the value in the form field.

Leave a Reply to richard Cancel reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">