WordPress: Photoswipe-lightbox integration with html-mockup in WP (without installing plugin)
Here I will briefly show how you can incorporate a lightbox feature into your gallery using PhotoSwipe v5.3.3.
Photoswipe is an open-source JavaScript-based image zooming gallery and consists of three parts:
- Core (photoswipe.esm.js).
- Lightbox (photoswipe-lightbox.esm.js) - loads Core and selects when PhotoSwipe should be opened. Its file size is significantly smaller. It also loads the first image (in parallel with Core).
- CSS (photoswipe.css) - a single file that controls all styling. There are no external assets for icons - they are all dynamically generated via JS and very small
The JS files are separated, so you can dynamically load Core only when the user needs it, reducing size.
The recommended way to use PhotoSwipe is to use a simple script type="module" tag. I include the code snippet in html (e.g. single-product.php) and as shown I download js and css files from a CDN network, so these don't need to be uploaded on the server. A script tag with the attribute type="module" indicates that it should be considered a javascript module.
import PhotoSwipeLightbox from 'https://unpkg.com/photoswipe/dist/photoswipe-lightbox.esm.js';
const lightbox = new PhotoSwipeLightbox({
gallery: '.gallery',
children: 'a',
bgOpacity: 0.5,
showHideAnimationType: 'zoom',
pswpModule: () => import('https://unpkg.com/photoswipe'),
});
lightbox.init();
I retrieve the CSS file via wp_enqueue_scripts (and only on post type "product" in this example).
add_action( 'wp_enqueue_scripts', 'register_styles', 10);
function register_styles() {
if (is_singular('product')) {
wp_enqueue_style('ps_css', 'https://unpkg.com/photoswipe@5.2.2/dist/photoswipe.css',[], 1, 'all' );
}
}
Html mark-up looks something like this
$images = []; //image array with all your images
$gallery = '<div class="gallery">';
foreach ($images as $img){
$image = getImgWithSizes($img, squareimg()); // my custom image function, which outputs different image sizes of the image in an array
$gallery .= '<a href="/en/'.$image['org']['0'].'/" target="_blank" rel="noopener" data-pswp-width="'.$image['org']['1'].'" data-pswp-height="'.$image['org']['2'].'" data-index="0">
<img src="'.$image['img']['url'].'" alt="'.$image['alt'].'" width="'.$image['img']['width'].'" height="'.$image['img']['height'].'" /> </a>';
}
$gallery .= '</div>';
echo $gallery;