Torben
Torben

Reputation: 5494

Using of the Wordpress Media Library is not working in my plugin

currently I try to include the wordpress media library within my plugin, but the url of the image is not copied into the respective input-field. When I debug the code and include alert(image_url); I get an "Undefined".

Does anybody know what I am doing wrong here? My code follows:

JS:

jQuery(document).ready(function() { 
    jQuery('#upload_logo_button').click(function() { 
        tb_show('Upload a logo', 'media-upload.php?referer=clb_plugin_options&type=image&TB_iframe=true&post_id=0', false); 
        window.send_to_editor = function(html) { 
            var image_url = $('img',html).attr('src'); 
            jQuery('#clb_setting_logo').val(image_url); 
            tb_remove(); 
        };     
        return false;
    });     
});//jquery document    

PHP:

public function admin_enqueue_scripts_func() {
    wp_enqueue_script('jquery');
    wp_enqueue_script('thickbox');
    wp_enqueue_script('media-upload');
    wp_register_script( 'js-script-clb-admin', plugins_url( 'js/clb-admin-min.js', dirname(__FILE__) ), array('jquery','media-upload','thickbox'));
    wp_enqueue_script( 'js-script-clb-admin');
}//function admin_enqueue_scripts_func  
add_action( 'admin_enqueue_scripts', 'admin_enqueue_scripts_func' );    

HTML:

<input type="text" id="clb_setting_logo" name="clb_plugin_options[clb_setting_logo]" value="<?php echo esc_url( $options['clb_setting_logo'] ); ?>" />
<input id="upload_logo_button" type="button" class="button" value="<?php _e( 'Upload Logo', 'clb' ); ?>" />

Upvotes: 0

Views: 1489

Answers (1)

Gavin Simpson
Gavin Simpson

Reputation: 2832

First off, Add wp_enqueue_media(); to admin_enqueue_scripts_func(). Try that for starters, as you are doing things very differently to what I have done recently (which works).

But from what I can tell, you use var image_url = $('img',html).attr('src');, but I don;t see

As a source of reference, here is my js.

var custom_uploader;
$(document.body).on('click', '#upload_image_button' ,function(e)
{
    e.preventDefault();
    if (custom_uploader)
    {
        custom_uploader.open();
        return;
    }
    custom_uploader = wp.media.frames.file_frame = wp.media(
    {
        title: 'Choose Image',
        button: {
            text: 'Choose Image'
        },
        multiple: false
    });
    custom_uploader.on('select', function()
    {
        attachment = custom_uploader.state().get('selection').first().toJSON();
        $('#upload_image').val(attachment.url);
    });
    custom_uploader.open();
});

Perhaps try this, replacing the id's with those of your own. Hope this helps a tad.

Upvotes: 1

Related Questions