Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

i have a custom post which has a meta tag that needs to be using a file upload (for video files). I am wondering, what is the correct way of adding an Upload button that points to the wordpress media uploader and set the url of the selected uploaded file to the text field that caused that associates the upload button.

I am not looking for code on creating the actual meta tag option, but for a way to actually add a Wordpress media upload button properly.

share|improve this question

2 Answers 2

up vote 4 down vote accepted

See this skeleton for use the media Uplaoder; is also use in your custom markup, like Meta Box.

A hint, check, that you only use the scripts on the page, where you active your Meta Box. Otherwise is it often a problem on the default pages and the uploader.

Now a attempt to clear the important parts to include the uploader to your custom part.

First include an button in the meta box:

<input id="upload_image" type="text" size="36" name="upload_image" value="" />
<input id="upload_image_button" type="button" value="Upload Image" />

Now enqueue the scripts:

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');
}

// better use get_current_screen(); or the global $current_screen
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');
}

The last part is your custom script to use the thickbox and the uploader inside this.

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

    $('#upload_image_button').click(function() {

        formfield = $('#upload_image').attr('name');
        tb_show( '', 'media-upload.php?type=image&amp;TB_iframe=true' );
        return false;
    });

    window.send_to_editor = function(html) {

        imgurl = $('img',html).attr('src');
        $('#upload_image').val(imgurl);
        tb_remove();
    }

});
share|improve this answer

Just a little reminder via the Codex page for admin_print_scripts:

admin_print_scripts mainly used to eco inline javascript. admin_print_scripts should not be used to enqueue styles or scripts on the admin pages. Use admin_enqueue_scripts instead.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.