DEV Community

Cover image for Utilising WordPress Media Library for Uploading Files
Kelin Chauhan
Kelin Chauhan

Posted on

Utilising WordPress Media Library for Uploading Files

The Blah Blah 😬

While developing custom functionality in WordPress plugins or themes most of the times major components are provided by WordPress-Core itself. One such component is WordPress’s Media Library. It’s a feature rich media handler that WordPress uses to let users upload images, videos, PDFs etc.

If you ever find your self in a situation where you need to implement uploading of files, try to use the WordPress’s Media Library instead of reinventing the wheel.

Unfortunately there’s not a lot of easily accessible help out there in WordPress Docs ( at least I couldn’t find easily ). The only most helpful resource I found is WordPress Media Javascript Guide. It’s a WordPress plugin that includes some example implementations and references. However again I found it not so easily accessible as you have to install the plugin in a WordPress installation and then browse through the links.

So here I’m writing this post in an attempt to provide a one stop reference to implement Custom usage of WordPress Media Library. Most of the examples and references are taken from WordPress Media Javascript Guide


✏️ The Post

Setting up the Media Library

You can use the WordPress Media Library by calling a helper function that is exposed through the window object.

var customMediaLibrary = window.wp.media({

    // Accepts [ 'select', 'post', 'image', 'audio', 'video' ]
    // Determines what kind of library should be rendered.
    frame: 'select',

    // Modal title.
    title: "'Select Images',"

    // Enable/disable multiple select
    multiple: true,

    // Library wordpress query arguments.
    library: {
        order: 'DESC',

        // [ 'name', 'author', 'date', 'title', 'modified', 'uploadedTo', 'id', 'post__in', 'menuOrder' ]
        orderby: 'date',

        // mime type. e.g. 'image', 'image/jpeg'
        type: 'image',

        // Searches the attachment title.
        search: null,

        // Includes media only uploaded to the specified post (ID)
        uploadedTo: null // wp.media.view.settings.post.id (for current post ID)
    },

    button: {
        text: 'Done'
    }

});

If you use frame: 'select' in the configuration then the resulting Media Library will be limited to selecting already uploaded media or uploading new media.

With frame set to select

frame: select

Or if you wish to include more options, such as Creating Gallery, Creating Audio Playlists, Creating Video Playlists etc then use frame: 'post'.

With frame set to post

frame: post

For opening the Media Libary

Just call the open() method of the media library object.


// Open the media uploader.
$( '#yourButtonID' ).on( 'click', function( e ) {
    e.preventDefault();
    customMediaLibrary.open();
});

For handling the selected images

You’ll have to attach a handler on the select event of the uploader and use a helper method customMediaLibrary.state().get( 'selection' ) to get the selected images.
This event is fired when the user selects the images and clicks on the select button.


customMediaLibrary.on( 'select', function() {

    // write your handling code here.
    var selectedImages = customMediaLibrary.state().get( 'selection' );

    // Probably send the image IDs to the backend using ajax?
});

For pre-selecting the images when Media Library is opened

You’ll need to attach a handler on the open event of the uploader.


customMediaLibrary.on( 'open', function() {

    // Assuming the post IDs will be fetched from db.
    var selectedPostIDs = [ 1, 2, 3, 4, 5 ];

    // Used for defining the image selections in the media library.
    var selectionAPI = customMediaLibrary.state().get( 'selection' );

    selectedImageIDs.forEach( function( imageID ) {
        /**
         * This returns an attachment object based on image ID 
         * or creates a new one if it doesn't exist in the wp.media.Attachments.allcollection.
         * Note: This does not fetch the image from db.
         */
        var attachment = wp.media.attachment( imageID );
        selectionAPI.add( attachment ? [ attachment ] : []);
    });

});

That’s all folks! This is all you need to implement the uploader.

Some other events / methods

These are some other events and methods that might be useful for advanced use cases / implementations of the Media Library.
For more detail you can refer to: WordPress Media Javascript Guide

// Fires after the uploader's markup has been built, but not appended to the DOM.
customMediaLibrary.on( 'ready', function() {} );

// Fires when the uploader's $el is appended to its DOM container.
customMediaLibrary.on( 'attach', function() {} );

// Fires when the modal opens (becomes visible).
customMediaLibrary.on( 'open', function() {} );

// Fires when the modal closes via the escape key.
customMediaLibrary.on( 'escape', function() {} );

// Fires when the modal closes.
customMediaLibrary.on( 'close', function() {} );

// Fires when a user has selected attachment(s) and clicked the select button.
customMediaLibrary.on( 'select', function() {
    var selectionCollection = customMediaLibrary.state().get('selection');
} );

// Fires when a state activates.
customMediaLibrary.on( 'activate', function() {} );

// Fires when a mode is deactivated on a region.
customMediaLibrary.on( '{region}:deactivate', function() {} );
// and a more specific event including the mode.
customMediaLibrary.on( '{region}:deactivate:{mode}', function() {} );

// Fires when a region is ready for its view to be created.
customMediaLibrary.on( '{region}:create', function() {} );
// and a more specific event including the mode.
customMediaLibrary.on( '{region}:create:{mode}', function() {} );

// Fires when a region is ready for its view to be rendered.
customMediaLibrary.on( '{region}:render', function() {} );
// and a more specific event including the mode.
customMediaLibrary.on( '{region}:render:{mode}', function() {} );

// Fires when a new mode is activated (after it has been rendered) on a region.
customMediaLibrary.on( '{region}:activate', function() {} );
// and a more specific event including the mode.
customMediaLibrary.on( '{region}:activate:{mode}', function() {} );

// Get an object representing the current state.
customMediaLibrary.state();

// Get an object representing the previous state.
customMediaLibrary.lastState();

// Open the uploader.
customMediaLibrary.open();

Top comments (1)

Collapse
 
niloys7 profile image
Niloy

Hi,
suppose i have #yourButtonID for open the wp media uploader. now i have an attribute (data-id="10") on the trigger button(#yourButtonID).
now, how can I get the attribute into the "select"

// Fires when a user has selected attachment(s) and clicked the select button.
customMediaLibrary.on( 'select', function() {

var selectionCollection = customMediaLibrary.state().get('selection');

} );