After setting up some basic markup in an earlier post I will enable my control to actually do something with those buttons.
[caption id=“attachment_755” align=“aligncenter” width=“996”] Seemingly useful control[/caption]
Hooking an action to the upload button
When the theme user clicks the Upload
button WordPress media uploader should appear.
To make sure that the scripts and styles associated with media uploader are loaded before attempting any action I will use the enqueue
method to load the media files
<?php
namespace tad\customizer\controls;
if (!class_exists('\WP_Customize_Control')) {
return null;
}
class MultiImageControl extends \WP_Customize_Control
{
public $type = 'multi-image';
public function enqueue()
{
wp_enqueue_media();
}
...
}
This method will override the parent class one, an empty method really, and will be executed any time the control is loaded. Following along the line drawn in post by Mike Jolley I will create a javascript file to bind the media uploader to the button markup code echoed by MultiImageControl::theButtons
method
<div>
<a href="#" class="button-secondary multi-images-upload">
<?php echo 'Upload'; ?>
</a>
<a href="#" class="button-secondary multi-images-remove">
<?php echo 'Remove images'; ?>
</a>
</div>
the script is located in assets/js/backstretch_block_admin.js
and actually does nothing but display the selected images urls
/*global console, jQuery, document, wp*/
jQuery(document).ready(function($) {
"use strict";
var file_frame;
jQuery('.multi-images-upload').live('click',
function(event) {
event.preventDefault();
// file frame already created, return
if (file_frame) {
file_frame.open();
return;
}
// create the file frame
file_frame = wp.media.frames.file_frame = wp.media({
title: jQuery(this).data('uploader_title'),
button: jQuery(this).data('uploader_button_text'),
multiple: true,
library: {
type: 'image'
}
});
// get the selected attachments
file_frame.on('select', function() {
var selected = file_frame.state().get('selection').toJSON(),
urls = [];
// store each image url in an hidden text field
for (var i = selected.length - 1; i >= 0; i--) {
console.log(selected[i].url);
}
});
// open the just created file frame
file_frame.open();
});
});
What’s happening now is that the Upload
button will actually allow the selection of one or more images but will do nothing but log those urls to the console. That’s as unuseful as it can get and I will use the information in the next iteration.