Storing multiple images in a metabox field using a custom WordPress media uploader instance


#1

This was a recent pain in the a… so decided to share some code in case somebody else had the misfortune of trying to do the same…



Goal was to use the native WordPress media uploader code to create a custom dialog that would be used for adding multiple images to a metabox (or page builder) field



Here’s a video showing what i’m blabbing about



Relevant javascript code


#2

Thanks! This looks really neat. I wonder how did you learn to customize the media uploader? It almost has no documentation although the rest of WordPress codes / files are quite well documented.


#3
billyf said

It almost has no documentation although the rest of WordPress codes / files are quite well documented.

true, that's why i decided to share the code. The only way to figure out how the thing works is by digging into source javascript files which can be quite tedious and time consuming.

#4

How did you create the button on this and popup the custom media uploader? thanks


#5

Thanks for sharing! OptionTree used the same type of meta field gallery, but I’ve never bother to check how they do it :wink:


#6

Just wanted to share, it could be shorter if you hack the [gallery] shortcode :slight_smile:

var gallery = wp.media.gallery;
var ids = []; // your current attachment ids
var frame = gallery.edit( '[gallery' + ( ids.length ? ' ids="' + ids.join( ',' ) + '"' : '' ) + ']' );

frame.state( 'gallery-edit' ).on( 'update', function( attachments ) {

	// `attachments` is an array of attachment objects
	console.log( attachments );

	// get all the attachment ids this way
	var ids = attachments.pluck( 'id' );
});
frame.on( 'close', function() { frame.detach(); });

or one line in your console:

wp.media.gallery.edit( '[gallery]' ).state( 'gallery-edit' ).on( 'update', function( attachments ) { console.log( attachments.pluck( 'id' ) ); } );