I need to use custom image field in wp plugin, everything works fine with upload/set function but have problem, when changing image: Problem: When i already have a image and need to replace i pick up new image from media library and submit, old one image stay visible so i have two images in view.
I asume that problem is with select function and append part, obviously i'm using wrong logic here, bellow are jquery+html of my code and screenshot of problem:
Problem(two images): First one should replaced with new selection image (second image)
This is my code:
$('#btn-upload-image').on('click', function(e) {
e.preventDefault();
var button = $(this);
var figure = button.siblings("figure");
var custom_uploader = wp.media({
title: 'Insert image',
library: { type : 'image' },
button: { text: 'Use this image' },
id: 'library-' + (Math.random() * 10),
multiple: false
}).on('select', function() {
var attachment = custom_uploader.state().get('selection').first().toJSON();
figure.append( $('<img/>', { 'src': attachment.url }) );
inputImage.val(attachment.url);
inputImageId.val(attachment.id);
})
.open();
});
and html:
<div class="form-group">
<label>Image</label>
<figure></figure>
<button type="button" class="btn btn-primary" id="btn-upload-image">Upload Image</button>
<input type="hidden" name="image" id="input-image" />
<input type="hidden" name="image_id" id="input-image-id" />
</div>