0

I am making a custom php page in wp-admin and required to upload multiple images and display it after upload and select images to display. Basically I would like to have the same effect as in Image Gallery of Gutenberg Wordpress. Is there any function to get the whole gallery block displayed on my php page?

Thank you.

1
  • ACF is exactly that. This plugin gives you the option to add custom fields (meta data) to option panel, posts, taxonomies, even menus. This will save you a lot of time of coding everything yourself Jun 24 at 7:06
2

wp.media is the JavaScript API WordPress uses to display the media library modal.

You can use it yourself by enqueueing a custom JS script on your admin page:

wp_enqueue_script('media-upload');
wp_enqueue_media();
wp_enqueue_script(
    'pb-admin-script',
    'admin.js',
    array(
        'jquery',
    )
);

Then work with it like this:

HTML:

<button class="upload_image_button button button-primary">
    <?php _e('Upload Image', 'pb'); ?>
</button>
<img src="" id="image-preview" style="display: none"/>

JS:

jQuery(document).ready(function($) {
    $(document).on('click', '.upload_image_button', function(event) {
        event.preventDefault();

        var imgPrev = $('#image-preview');

        var file_frame = wp.media.frames.file_frame = wp.media({
            title: 'Select or upload image',
            library: {
                type: 'image'
            },
            button: {
                text: 'Select'
            },
            multiple: false,
        });

        file_frame.on('select', function() {
            var attachment = file_frame.state().get('selection').first().toJSON();

            imgPrev.src = attachment.url;
            imgPrev.style.removeProperty('display');
        });

        file_frame.open();
    });

});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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