admin管理员组

文章数量:1289877

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.

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.

Share Improve this question asked Jun 24, 2021 at 3:45 murnimurni 376 bronze badges 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 – Buttered_Toast Commented Jun 24, 2021 at 7:06
Add a comment  | 

1 Answer 1

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

});

本文标签: imagesHow to get the Gallery formsection just like in Gutenberg block