0

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)

Two images screenshot

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>

1 Answer 1

1

Here's the problem:

figure.append( $('<img/>', { 'src': attachment.url }) );

append inserts content at the end of the target element, maintaining existing content in place. What you want in this case is to replace whatever is in there with new content (the new image), so:

figure.html( $('<img/>', { 'src': attachment.url }) );

html replaces any content that was in the targeted element(s) with the new one.

Hope that helps!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.