Wiring WordPress Media Uploader Into Your Web App

As predicted, the “premium” theme I purchased to make things happen on the HereMusic.Live site needs more tweaking.  Today I am diving into the proper way to wire the WordPress media uploader into a plugin after learning the theme not only cannot handle a media file with parenthesis in the name but it also is dropping the media title into the URL field on the form.  Ugh.

Most of the magic for the WordPress Media interface is managed via JavaScript.    I’m going to focus on the JavaScript portion of the code, assuming an app already has a basic form on an admin page that needs media uploaded and gets the URL put into a form element.   I’m also going to assume you know how to attach basic “on click do this” to an HTML element using jQuery or inline onClick methods.

Rip Out Thickbox

The old-school method of attaching to the WordPress media uploader was to tie into the Thickbox-driven media interface.   If you look into an existing WordPress plugin or theme and see the JavaScript littered with tb_show() and window.send_to_editor references there is a very good chance it is using the outdated Thickbox model.

function addUploaderFunctionToButton(upButt){
    upButt.click(function(e) {
        formID = $(this).attr('rel');
        formfield = $(this).siblings('.meta_box_upload_file');
        preview = $(this).siblings('.meta_box_filename');
        icon = $(this).siblings('.meta_box_file');
        tb_show('Choose File', 'media-upload.php?post_id=' + formID + '&type=file&TB_iframe=1');             
        window.orig_send_to_editor = window.send_to_editor;
        window.send_to_editor = function(html) {
            var hasMarkup = ( html !== $('<div></div>').html(html).text() );
            var file_url;
            if (hasMarkup) {
                file_url = $(html).attr('href');
                formfield.val(file_url);
            } else {
                file_url = html;
            }
            preview.text(file_url);
            // icon.addClass('checked');    This thing is gone and never worked anyway
            //var selector =  '.meta_box_upload_file_button[rel="'+formID+'"]';
            //jQuery( selector ).val('Change');
            tb_remove();
            window.send_to_editor = window.orig_send_to_editor;
        };
    });
}

I’m not sure where this model is breaking down on my WordPress 4.7 site but somehow the html parameter on the send_to_editor() call is only receiving a string containing the file title.

Time to rip it out and replace it with the thinner and generally better-designed wp.media model.  It was introduced eons ago (in modern web app terms) and should be the go-to method for implementing this feature.

Insert wp.media

As with many of the “black magic” features of WordPress, wp.media is not well documented on the new developer guides and function references.   Most of the knowledge we’ll need has to come from the “old” Codex wp.media pages.

The basic concept is simple:  When the user clicks the add button create a new wp.media JavaScript object and open it.

wp.media Details

We start by defining a media_frame variable in JavaScript at a global scope so we can make it a singleton; in essence don’t fire up a new popup wp.media form every time someone clicks the button.

Next we attach an anonymous function to the click event on the button that will do some general maintenance, set some properties for the wp.media object, and tell that object what we want to do when the user selects a file.   Remember that whether the user has just uploaded a new file or picked from an existing file the application considers this a ‘select’ action in either case.    The last step of this click function is to open the wp.media object which fires up the standard WordPress upload/select window.

Example Details

The initial implementation:

/**
 * Process Upload Button Click
 *
 * @param the_button
 */
function addUploaderFunctionToButton( the_button ){

    /**
     * button click function
     */
    the_button.on( 'click' , function( event ) {
        event.preventDefault();

        // If the media frame already exists, reopen it.
        if ( media_frame ) {
            media_frame.open();
            return;
        }

        // Create a new media frame
        media_frame = wp.media({
            title: 'Select or Upload A File',   // Should pass via localized script variable for i18n/l10n
            button: { text: 'Use This' },       // Should pass via localized script variable for i18n/l10n
            multiple: false                     // Set to true to allow multiple files to be selected
        });


        // When the file is selected in the media frame...
        var url_field = jQuery( this ).siblings( '.meta_box_upload_file' );
        media_frame.on( 'select', function() {

            // Get the details about the file the user uploaded/selected
            var attachment = media_frame.state().get('selection').first().toJSON();

            url_field.val( attachment.url);
        });

        // Finally, open the modal on click
        media_frame.open();
    });

}

Always preventDefault() on these actions to prevent conflicts with other things that may be attached to the click event stack in  your web app or browser.

Check if the media_frame global variable is active.  If it is then our media form is open somewhere.   Re-open it (show it) and leave.  This cuts down on the overhead of re-creating the window object every time we click the button.

Create the wp.media object and attach it to the media_frame variable.  This is a single instance of the media selector.  Pass in some attributes for the window title, button label, and multiple selection options.   Later we’ll use localize_script() in the PHP side of the code so we have an app that is gettext() , and thus i18n/l10n, compatible.

Before we get into the frame  processing ,  grab a sibling field on the HTML form that contains the add button we clicked to fire up the form.  My example HTML form has an input text field with the class mea_box_upload_file where we put the URL for the file we are selecting.

The select is processed with an .on( ‘select’ … ) trigger.    When the user clicks the “Use This” button (our label for the select button) it will fire the anonymous function defined here.   The details of the file they selected is retrieve in the media_frame.state().get(‘selection’).first().toJSON() call.    I then use the variable I set earlier that points to my URL field on my HTML form and set the value to the file’s url property.

With all the triggers and properties set for the media window I can now open the media selector as the last step of the button click process.

Follow Up Feb 1 2017

Additional notes and a complete code example.

First – wp.media has a frames property where you can (should?) attach your active frame instead of managing it “by hand” within your JavaScript.

Second – return false from the function that you invoke the media from.   Depending on where you call your modal open() you may get the entire stack of media windows opening.  In my plugin I was getting my custom modal plus a default modal provided by WordPress on an admin setting page.

Third – I’ve refactored the default code you see on nearly EVERY example of doing the frame open where it first checks to see if the frame exists, if it does return frame.open() and if it does not do the setup then return frame.open().   Nearly every time you call the same method twice within a few lines of code it can be refactored to be more efficient.  That is included in my example.

New Example

This is from my Store Locator Plus code.    I use a block scope variable that I change every time a user clicks a button so I know which setting to update with the image URL the user selected.    This allows the on(‘select’) code for the window frame itself to remain static.  Better caching and code compression can happen with this setup.

/**
 * Icon Helper
 * @constructor
 */
var SLP_Admin_icons = function () {
    var active_setting;

    /**
     * Initialize the icon interface.
     */
    this.initialize = function() {
       this.connect_wp_media_to_insert_media_buttons();
   };

    /**
     * Fire up WP Media selector on insert media buttons.
     */
   this.connect_wp_media_to_insert_media_buttons = function() {
       jQuery('.input-group .wp-media-buttons .insert-media').on( 'click' , function( event ) {
           event.preventDefault();
           var setting = jQuery( this ).attr( 'data-field' );
           SLP_Admin_Settings_Help.icons.active_setting = setting.replace(/(:|\.|\[|\])/g,'\\$1');
           SLP_Admin_Settings_Help.icons.create_media_frame();
           return false;
       });

       /**
        * Create the tweaked WP Media frame, make it a singleton.
        */
       this.create_media_frame = function () {
           if ( ! wp.media.frames.slp_icon_frame ) {
               wp.media.frames.slp_icon_frame = wp.media({
                   title: 'Select or Upload An Icon',   // TODO: pass via localized script variable for i18n/l10n
                   button: { text: 'Use This' },       // TODO: pass via localized script variable for i18n/l10n
                   multiple: false,
                   library: {
                       type: 'image'
                   }
               });

               wp.media.frames.slp_icon_frame.on( 'select', function() {

                   // Get the details about the file the user uploaded/selected
                   var attachment = wp.media.frames.slp_icon_frame.state().get('selection').first().toJSON();

                   jQuery('#'+SLP_Admin_Settings_Help.icons.active_setting).val( attachment.url);
                   jQuery('#'+SLP_Admin_Settings_Help.icons.active_setting+'_icon').attr( 'src', attachment.url);

               });
           }

           wp.media.frames.slp_icon_frame.open();

       };
   }
};

/**
 * Locations Tab Admin JS
 */
jQuery(document).ready(
    function() {
        if ( jQuery( '.wp-media-buttons' )[0] ) {
            SLP_Admin_Settings_Help.icons = new SLP_Admin_icons();
            SLP_Admin_Settings_Help.icons.initialize();
        }
    }
);

The class the creates the HTML code.  Obviously a partial example as this web app uses all kinds of objects and inheritance to manage oft-repeated code segments.

		/**
		 * Need media library for this.
		 */
		public function at_startup() {
			wp_enqueue_media();
		}

		/**
		 * The icon HTML.
		 *
		 * @param string $data
		 * @param string $attributes
		 *
		 * @return string
		 */
		protected function get_content( $data, $attributes ) {
			$icon_src = ! empty( $this->display_value ) ? $this->display_value : $this->slplus->SmartOptions->map_end_icon;

			return
				"<input type='text' id='{$this->id}' name='{$this->name}' {$data} value='{$this->display_value}' {$attributes}/>" .
				"<img id='{$this->id}_icon' alt='{$this->id}' src='{$icon_src}' class='slp_settings_icon'>" .
				$this->media_button_html( $data ) .
				$this->slplus->AdminUI->create_string_icon_selector( $this->id, $this->id . '_icon' )
				;
		}

		/**
		 * Set the media button HTML
		 *
		 * @param string $data
		 *
		 * @return string
		 */
		private function media_button_html( $data ) {
			return
				 '<div class="wp-media-buttons">' .
					 "<button type='button' class='button insert-media add_media' {$data}>".
						'<span class="dashicons dashicons-admin-media"></span>'.
					    __( 'Use Media Image' ) .
					'</button>' .
				'</div>'
				;
		}

	}

JavaScript: wp.media

The Codex says… JavaScript Reference wp.media.

wp_enqueue_media()

This magic WordPress function will enqueue all of the JavaScript elements needed to work with the media uploader provided by WordPress core.

Needs to be fired in/after admin_enqueue_scripts in the call stack.

The Codex says… wp_enqueue_media() 

The Code Reference says… wp_enqueue_media().

One thought on “Wiring WordPress Media Uploader Into Your Web App

  1. Hi, thank you for this very well explained article. i may have a question concerning the differences between the thickbok model, who used to feature the many tabs that we find in can define with the media_upload_tabs hook/filter, and this new wp.media model…
    I ve been struggling on this for days… you may have an hint…

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.