Last active
December 13, 2021 23:22
-
-
Save wpexplorer/96951068a6c8de1e618639d002341337 to your computer and use it in GitHub Desktop.
Include all post galleries in the lightbox.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
add_action( 'wp_footer', function() { | |
wp_enqueue_script( 'jquery' ); | |
?> | |
<script> | |
document.addEventListener( 'click', function( event ) { | |
var target = event.target.closest( '.gallery-item a' ); | |
if ( ! target ) { | |
return // not a gallery item | |
} | |
// The current link we are clicking on. | |
var currentLink = target.getAttribute( 'href' ); | |
if ( ! currentLink ) { | |
return; // item doesn't have a link. | |
} | |
// Note: you could add a complex check here as well to ensure the gallery item is linking to an image | |
// and not an attachment page. | |
// Prevent click event since we want to display lightbox. | |
event.preventDefault(); | |
// Get parent post container. | |
var parent = target.closest( '#content' ); | |
if ( ! parent ) { | |
return; // not a gallery inside a post | |
} | |
// Define array for gallery items. | |
var galleryItems = []; | |
// Define active index to ensure the item we are clicking on is the item shown in the lightbox. | |
var activeIndex = 0; | |
// Loop through all post gallery images and save in an array. | |
document.querySelectorAll( '.gallery-item a' ).forEach( function( galleryItemLink, index ) { | |
var link = galleryItemLink.getAttribute( 'href' ); | |
if ( link ) { | |
galleryItems.push( { | |
src: link, | |
opts: { thumb: link } | |
} ); | |
} | |
if ( link === currentLink ) { | |
activeIndex = index; | |
} | |
} ); | |
// Trigger lightbox. | |
if ( galleryItems | |
&& 'object' === typeof wpex_fancybox_params | |
&& 'function' === typeof jQuery | |
&& 'undefined' !== typeof jQuery.fancybox | |
) { | |
jQuery.fancybox.open( galleryItems, wpex_fancybox_params, activeIndex ); | |
} | |
} ); | |
</script> | |
<?php }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment