Ekko Lightbox is a super nice, Bootstrap-friendly lightbox library that can easily be made to play well with Sage 9 and WordPress galleries. Check it:
Install Ekko Lightbox
$ yarn add ekko-lightbox
Import in Javascript
At the top of the appropriate route (probably common.js
), import ekko-lightbox:
import 'ekko-lightbox/dist/ekko-lightbox.js';
Add your javascript
In the same route, probably in finalize
, add your custom javascript:
/**
* Prevent default click behavior on WordPress gallery image links
*/
$(document).on('click', '.gallery-item a', function(event) {
event.preventDefault();
$(this).ekkoLightbox();
});
// Make an ekko lightbox out of WordPress galleries
$('.gallery a[href]')
// Test whether this link is directly to an image file
.filter(function() {
return /(jpg|gif|png)$/.test($(this).attr('href'));
}).each(function() {
// Get link attr
var link = $(this).attr('href');
// Get the image ALT text
var alt = $(this).find('img').attr('alt');
// Strip the file extension
var filename = link.substr(0, $(this).attr('href').lastIndexOf('.')) || $(this).attr('href');
// Get the index of just the filename without the path
var fileNameIndex = filename.lastIndexOf("/") + 1;
// Return just the filename without the path and without the extension
filename = filename.substr(fileNameIndex);
// Get the ALT text so we can use it as a caption ONLY if it's NOT the same as the filename!
// WordPress automatically uses the filename as ALT text if no caption or ALT is set, so we don't want to use it if they're the same.
var caption = (filename === alt) ? '' : alt;
// Get the gallery ID
var gallery = $(this).closest('.gallery').attr('id');
// Add ekko lightbox data-attributes
$(this).attr({'data-toggle': 'lightbox', 'data-gallery': gallery, 'data-footer': caption});
});
Optional: set the default gallery options to link to media files
By default, WordPress gallery items link to attachment pages, rather than media files. We can change this default in the admin.
Note: this will only change the default for newly created galleries; old galleries will maintain the settings they were created with!
Create a new file in app
called galleries.php
:
<?php
namespace App;
/**
* Set default link type for WordPress galleries
*/
add_filter( 'media_view_settings', function($settings) {
$settings['galleryDefaults']['link'] = 'file';
return $settings;
});
Update functions.php
line 61 to add galleries
:
...
}, ['helpers', 'setup', 'filters', 'admin', 'galleries']);