My Old Question:
I made a Theme with rotating banner,
common thing. So I want a way for
users to select images. I think
instead of implementing my own upload,
I think its better to allow users to
use the Media Library, how do I do
that?
The New One
So far, I have something like below
functions.php
// init wordpress media upload stuff ...
if (is_admin() && isset($_GET['page']) && $_GET['page'] == 'elem_opts') {
wp_enqueue_style('thickbox');
wp_enqueue_script('media-upload');
wp_enqueue_script('thickbox');
wp_register_script('elem_adm_js', get_bloginfo('template_directory') . '/js/admin.js', array('jquery', 'media-upload', 'thickbox'));
wp_enqueue_script('elem_adm_js');
}
admin.js
jQuery(document).ready(function($) {
$('#elem_upload_logo').click(function() {
tb_show('', 'media-upload.php?type=image&TB_iframe=true');
return false;
});
window.send_to_editor = function (html) {
imgurl = $('img', html).attr('src');
$('input[name=elem_opts[h_image]]').val(imgurl);
tb_remove();
}
});
The media library upload thickbox pops up, I can click select files, but when I try to upload them nothing happens. In Firebug I can see the following:
Here are 3 links to get you started, your question should be more clear, do you want this to work like twentyten’s header, using a custom theme options field, a category?
How to use media upload on theme option page?
How can I add an image upload field directly to a custom write panel?
Attaching media to custom posts without editor
Creating an Image-Centric Custom Post Type?
1) I think you should change the JS file. The
send_to_editor
is the default WordPress handler that will insert image into the editor. In your code, you completely replaced it. That’s not cool. You should backup it (I’m not sure if that can fix the errors, but at least it make your code run more properly):Something in this code I’ll explain below
2) Another problem with your code is that the returned
html
might has noimg
tags. Actually, it depends on how users choose the way to link the image (they can link the image to the attachment page, the image file, or not link to anywhere). The code above works only when the image is linked to the image file.You can test this situation by inserting image to the editor, changing the way image is linked, you’ll see the actual returned html.
3) The last problem I found when viewing your errors is that you didn’t declare the post ID. The thinkbox media uploader must have post ID.
To fix this, you can use a simple trick: in your PHP code that echos the
#elem_upload_logo
, set itsrel="<?php echo $post->ID; ?>"
and in your JS script, extract this attribute and pass it into the URL of the media uploader (as the code above).