I spent a few hours playing around with code which I seem to be getting close?
Writing the following jQuery does load the right id’s but doesn’t initiate the lightbox:
$(“.tiled-gallery”).each(function(i) {
var galleryCount = $(this)
galleryCount.attr(‘id’, ‘gallery-‘ + i);
i++;
});
document.addEventListener(‘DOMContentLoaded’, function() {
// Select all divs with an ID starting with ‘gallery-‘
document.querySelectorAll(‘div[id^=”gallery-“]’).forEach(function(galleryDiv) {
// For each gallery item within this gallery div
galleryDiv.querySelectorAll(‘.tiled-gallery-item’).forEach(function(galleryItem) {
// Retrieve the text inside the figcaption element.
var caption = galleryItem.querySelector(‘.the-image-title’)?.textContent || ”;
// Add the data-sub-html attribute to the corresponding <a> element
galleryItem.querySelector(‘a’).setAttribute(‘data-sub-html’, caption);
});
// Get the ID of the current div
var id = galleryDiv.getAttribute(‘id’);
// Use a regular expression to extract the number from the ID
var number = id.match(/\d+/)[0];
// Initialize lightGallery
lightGallery(galleryDiv, {
plugins: [lgAutoplay, lgComment, lgFullscreen, lgHash, lgRelativeCaption, lgShare, lgThumbnail, lgVideo, lgZoom],
selector: ‘a’,
galleryId: number,
});
});
});
When I modify the PHP output of tiled-gallery.php and manually add id=”gallery-0″ this allows the gallery to function. However each gallery URL hash is set to gallery 0 (first gallery) despite the DOM being dynamically changed via JS to have id’s gallery-1, gallery-2, gallery-3. I tried adding a setTimeout function but that changed nothing. In other words it seems the gallery initiation reads the PHP output such as <div id=”gallery-0″> but not when the id’s are created through jQuery. I’ve tried multiple variations including just having jQuery generate the ids. I’d love to loop through each .tiled-gallery item via PHP which I’m certain would fix the hash problem, however I cannot for the life of me figure out how to count the .tiled-gallery objects. I placed the loop counter outside foreach, created a global var + initiated 0, created a imageCount++, placed it in various loops, reconstructed into custom function, ect. I’ve been able to count the gallery rows/individual images. But the counter resets on the next gallery.
If there is a way for lightgallery to see the div’s with id’s gallery-1, gallery-2, gallery-3 that was generated from jQuery this would in theory initiate the gallery.