Skip to content

Latest commit

 

History

History
87 lines (65 loc) · 3.54 KB

File metadata and controls

87 lines (65 loc) · 3.54 KB

WordPress-Media-Modal-Image/File-Uploads

This is a sample to show how you can open the admin media modal and how to get a single or multiple images/files selected via the WordPress admin media modal. Tested with WordPress Version 6.0
SCREENSHOTS AVAILABLE AT THE BOTTOM OF THE WEB PAGE

Enqueue your javascript file and all media JS APIs.

Enqueue your javascript file and all media JS APIs.

    add_action('admin_enqueue_scripts', function() {
        wp_enqueue_media(); // Enqueues all scripts, styles, settings, and templates necessary to use all media JS APIs.
        wp_enqueue_style("sample.js", "your-path/sample.js", array(), "1.0.0", false);
    });

HTML SAMPLE

(a) href="#" id="open_modal_link">Open Modal (/a)

How to open the Media Frame & Get Info for a single image/file

    // Select open modal link
    let open_modal_link = document.getElementById("open_modal_link");
    
    open_modal_link.addEventListener("click", function(e) {
            e.preventDefault();
            // Creates a new media frame
            let frame = wp.media({
                title: "Add Your Own Title Here",
                button: {
                    text: 'Add Your Own Text Here'
                },
                multiple: false
            });
            frame.open();

            // When an image is selected in the media frame...
            frame.on('select', function() {

                // Get media attachment details from the frame state
                let attachment = frame.state().get('selection').first().toJSON();
                // Log the attachment object for more info
                console.dir(attachment);
                // Get the Image URL from the attachment object
                let image_url = attachment.url;
            });
    });

How to open the Media Frame & Get Info for a Multiple Images/Files

    // Select open modal link
    let open_modal_link = document.getElementById("open_modal_link");

    open_modal_link.addEventListener("click", function(e) {
            e.preventDefault();
            // Creates a new media frame
            let frame = wp.media({
                title: "Add Your Own Title Here",
                button: {
                    text: 'Add Your Own Text Here'
                },
                multiple: true
            });
            frame.open();

            // When multiple images are selected in the media frame...
            frame.on('select', function() {

                // Get media attachment details from the frame state
                let attachment = frame.state().get('selection').toJSON();
                // Log the Array
                console.dir(attachment);
            });
    });

SCREENSHOTS

test1 test2 test3 test4 test5 test6