igmoweb
3/12/2018 - 1:46 PM

media-wp.jsx

const postId = 1000;
const frames = {};

/**
 * Get a Media Modal instance for a given item ID
 *
 * @param itemId
 * @return {object}
 */
function getMediaFrame( itemId ) {
	if ( frames[ itemId ] ) {
		return frames[ itemId ];
	}

	const options = {
		title:    'Select teaser image',
		button:   { text: 'Add the teaser image' },
		multiple: false,
		frame: 'post'
	};

	window.wp.media.view.settings.post = {
		id: itemId
	};

	frames[ itemId ] = window.wp.media( options );
	return frames[ itemId ];
}

/**
 * Open an instance of Media Modal and execute a callback when a picture is selected
 *
 * @param itemId
 * @param callback
 */
export function openMediaFrame( itemId, callback ) {
	const frame = getMediaFrame( itemId );
	frame.on( 'insert', () => {
		callback.apply( null, [ frame ] );
		frame.reset();
	} );
	frame.open();
}




openMediaFrame( postId, ( frame ) => {
	// Do something
});