A weird issue happening with me which I am unable to fix. In my theme options page, I added options to upload images one for logo and another for backgroud image. Here is my HTML
<table class="form-table">
<tr>
<th scope="row"><?php _e('Logo Image'); ?></th>
<td><label for="logo_link">
<input id="image-url" type="text" name="logo_link" value="<?php echo get_option('logo_link'); ?>" size="50" />
<input id="upload-button" class="button" type="button" value="Upload Image" />
</label>
</td>
</tr>
<tr>
<th scope="row"><?php _e('BG Image'); ?></th>
<td><label for="bg_image">
<input id="image-url" type="text" name="bg_image" value="<?php echo get_option('bg_image'); ?>" size="50" />
<input id="upload-button" class="button" type="button" value="Upload Image" />
</label>
</td>
</tr>
</table>
This how I enqueued the JS
function media_uploader_enqueue()
{
wp_enqueue_media();
wp_register_script('image-upload-js', get_stylesheet_directory_uri(). '/js/image-upload-js.js', true, '1.0.1');
wp_enqueue_script('image-upload-js');
}
add_action('admin_enqueue_scripts', 'media_uploader_enqueue');
This is what I put in the image-upload-js.js
file
jQuery(document).ready(function($){
var mediaUploader;
$('#upload-button').click(function(e) {
e.preventDefault();
if (mediaUploader) {
mediaUploader.open();
return;
}
mediaUploader = wp.media.frames.file_frame = wp.media({
title: 'Choose Image',
button: {
text: 'Choose Image'
}, multiple: false });
mediaUploader.on('select', function() {
attachment = mediaUploader.state().get('selection').first().toJSON();
$('#image-url').val(attachment.url);
});
mediaUploader.open();
});
});
The annoying problem
The media uploader is opening for Logo Image field but not for the BG Image. I can also save options and all is set. If I put the URL manually in the BG image text field, it’s file. Just the media uploader is not working for this. If I shift the HTML block, the uploader only opens for the first block only. Any reason why this is happening. Thanks