On one of my custom posts edit page I have a button that triggers the media popup onclick, with: wp.media.editor.open(); and while it brings up the media manager I’m not sure if that’s the proper way to do it. Is it?

But real question is about something else. How do I attach event listeners to various events that media popup should trigger? Like open or close or is there any event for switched view?

2 Answers
2

You can use several event handlers.

frame.on('open',function() {
    // Do something
});

frame.on('close',function() {
    // Do something
});

frame.on('select',function() {
    // Do something
});

Where frame is a reference to wp.media()

frame = wp.media();

frame.on('select',function() {
    // Do something
});

Full example

Script en-queued with jQuery and media editor as dependencies.

function media_script_enqueue() {
   wp_enqueue_script( 'media-script', get_template_directory_uri() . '/js/media-script.js', array( 'jquery', 'media-editor' ), '', true );
}
add_action( 'wp_enqueue_scripts', 'media_script_enqueue' ); // Front-end
add_action( 'admin_enqueue_scripts', 'media_script_enqueue' ); // Back-end

Script contains:

;( function( $ ) {
    var frame = wp.media({
         multiple: true
    });

    $(".media").on("click", function(e) {
        frame.open();

        e.preventDefault();
    });

    frame.on('open', function() {
        console.log("Open");
    });

    frame.on('close', function() {
        console.log("Close");
    });

    frame.on('select', function() {
        console.log("Select");

        var selection = frame.state().get('selection');

        selection.each(function(attachment) {
            console.log(attachment.id);
        });
    });
} )( jQuery );

Window triggered by a button with a classname of media

<button class="media">Media</button>

Media javascript dependencies enqueued via function.

<?php wp_enqueue_media(array('post' => get_the_ID())); ?>

Leave a Reply

Your email address will not be published. Required fields are marked *