0

I am trying to add a second featured image to the Wordpress post editor, and it seems all be working. When I select and image from the mediauploader the first time the image shows in the preview of the metabox. However when I want change an image of the second featured image, I have to save the post first and than i seeing the change, it doesn't change immediately. Can some help please. Thanks

This is my second-featured-image-meta-box.php

<?php
// Add meta box for second featured image
function add_second_featured_image_meta_box() {
    $post_types = array('project');  // Adjust this to your post types

    foreach ($post_types as $post_type) {
        add_meta_box(
            'second_featured_image_meta_box',
            'Second Featured Image',
            'display_second_featured_image_meta_box',
            $post_type,
            'side',
            'default'
        );
    }
}

// Display content of the second featured image meta box
function display_second_featured_image_meta_box($post) {
    $second_featured_image = get_post_meta($post->ID, '_second_featured_image', true);
    ?>

    <style>
        .image-preview img {
            max-width: 100%;
            height: auto;
            cursor: pointer;
        }
        .edit-image-link,
        .remove-image-link {
            margin-top: 5px;
            display: block;
        }
    </style>

    <label for="second_featured_image">Second Featured Image:</label>
    <div class="image-preview" id="second_featured_image_preview">
        <?php if (!empty($second_featured_image)) : ?>
            <?php echo wp_get_attachment_image($second_featured_image, 'full'); ?>
        <?php endif; ?>
    </div>
    <button class="upload-image-button button" id="upload_second_featured_image_button">Upload/Select Image</button>
    <button class="remove-image-button button" id="remove_second_featured_image_button" <?php echo empty($second_featured_image) ? 'style="display: none;"' : ''; ?>>Remove Image</button>

    <input type="hidden" id="second_featured_image" name="second_featured_image" value="<?php echo esc_attr($second_featured_image); ?>" style="width: 100%;">

    <?php
}

// Save the second featured image when the post is saved
function save_second_featured_image_meta_box($post_id) {
    if (isset($_POST['second_featured_image'])) {
        $second_featured_image = absint($_POST['second_featured_image']); // Use absint to ensure it's an integer
        update_post_meta($post_id, '_second_featured_image', $second_featured_image);

        // Check if the remove image button was clicked
        if (isset($_POST['remove_second_featured_image']) && $_POST['remove_second_featured_image'] === 'true') {
            delete_post_meta($post_id, '_second_featured_image');
        }
    }
}

// Hook to add meta box
add_action('add_meta_boxes', 'add_second_featured_image_meta_box');

// Hook to save meta box data
add_action('save_post', 'save_second_featured_image_meta_box');
?>

and this is my javascript:

jQuery(document).ready(function ($) {
    let mediaUploader = wp.media({
        title: 'Choose Image',
        button: {
            text: 'Choose Image'
        },
        multiple: false
    });

    mediaUploader.on('select', function () {
        var attachment = mediaUploader.state().get('selection').first().toJSON();
        $('#second_featured_image').val(attachment.id);
        $('#second_featured_image_preview').attr('src', attachment.url).show();
        $('#upload_second_featured_image_button').text('Change Image');
        $('#remove_second_featured_image_button').show();
    });

    function removeFeaturedImage() {
        $('#second_featured_image').val('');
        $('#second_featured_image_preview').attr('src', '').hide();
        $('#upload_second_featured_image_button').text('Set Featured Image');
        $('#remove_second_featured_image_button').hide();
        return false;
    }

    // On page load, hide the "Remove Image" button if no image is selected
    if ($('#second_featured_image').val() === '') {
        $('#remove_second_featured_image_button').hide();
    }

    $('#upload_second_featured_image_button').on('click', function (e) {
        e.preventDefault();
        mediaUploader.open();
        console.log("Works");
    });

    // Add click event for the "Remove Image" button
    $('#remove_second_featured_image_button').on('click', function (e) {
        e.preventDefault();
        removeFeaturedImage();
    });
});

1 Answer 1

0

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();
    });
});

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.