The issue you’re experiencing, where the image preview in the meta box doesn’t update immediately when you change the second featured image, is likely due to the way the image preview is being handled in your jQuery code. To resolve this, you need to ensure that the image preview updates in real-time as soon as a new image is selected from the media uploader, without requiring a post save to see the change.
Here’s an updated version of your jQuery script with modifications to handle the immediate preview update:
jQuery(document).ready(function ($) {
let mediaUploader;
$('#upload_second_featured_image_button').on('click', function (e) {
e.preventDefault();
// If the uploader object has already been created, reopen the dialog
if (mediaUploader) {
mediaUploader.open();
return;
}
// Extend the wp.media object
mediaUploader = wp.media({
title: 'Choose Image',
button: {
text: 'Choose Image'
},
multiple: false
});
// When an image is selected, run a callback
mediaUploader.on('select', function () {
var attachment = mediaUploader.state().get('selection').first().toJSON();
$('#second_featured_image').val(attachment.id);
// Update the image preview
var imagePreview = $('#second_featured_image_preview');
if (imagePreview.length) {
imagePreview.html('<img src="' + attachment.url + '" style="max-width: 100%; height: auto;">');
} else {
// If the preview element doesn't exist, create it
$('#second_featured_image_container').append('<div id="second_featured_image_preview"><img src="' + attachment.url + '" style="max-width: 100%; height: auto;"></div>');
}
$('#upload_second_featured_image_button').text('Change Image');
$('#remove_second_featured_image_button').show();
});
// Open the uploader dialog
mediaUploader.open();
});
$('#remove_second_featured_image_button').on('click', function (e) {
e.preventDefault();
$('#second_featured_image').val('');
$('#second_featured_image_preview').html('');
$('#upload_second_featured_image_button').text('Set Featured Image');
$(this).hide();
});
});