I have a new theme I'm working on and I really need 3 image upload options which trigger the popup media upload box.
I know the customizer is recommended now but it only really makes sense to me to use that for styles (ie. colours and fonts) and still have a theme settings section which is what I have done.
After trying many solutions, Rushabh Dave's solution here works a treat, nearly perfect but not quite...
My issue is I get the popup box, select the image and I then have the URL to that image but when I hit save, the page refreshes but my image isn't saved, the URL disappears therefore I can't pick it up the front end.
I'm not sure what I may be doing wrong.
In functions.php
<?php
// jQuery
wp_enqueue_script('jquery');
// This will enqueue the Media Uploader script
wp_enqueue_media();
?>
<div>
<label for="image_url">Image</label>
<input type="text" name="image_url" id="image_url" class="regular-text" />
<input type="button" name="upload-btn" id="upload-btn" class="button-secondary" value="Upload Image">
</div>
<script type="text/javascript">
jQuery(document).ready(function($){
$('#upload-btn').click(function(e) {
e.preventDefault();
var image = wp.media({
title: 'Upload Image',
// mutiple: true if you want to upload multiple files at once
multiple: false
}).open()
.on('select', function(e){
// This will return the selected image from the Media Uploader, the result is an object
var uploaded_image = image.state().get('selection').first();
// We convert uploaded_image to a JSON object to make accessing it easier
// Output to the console uploaded_image
console.log(uploaded_image);
var image_url = uploaded_image.toJSON().url;
// Let's assign the url value to the input field
$('#image_url').val(image_url);
});
});
});
</script>
On the front-end
<div><img src="<?php echo $options['image_url']; ?>" /></div>