Create a gallery with a custom lightbox

Since the addition of the blocks editor in WordPress, you can add a Lightbox to a gallery. However, the information in this article is still relevant if you would like to add you own Lightbox.

Learn to create a gallery with a lightbox which allows you to click the image and view it in an overlay. It also adds navigation (a next and previous arrow to quickly go through the images in the gallery).

Create a gallery with WordPress first:

Then, click upload or media library to add images.

Under the Block settings, Popup Controls, do NOT enable the Lightbox.

The gallery might look like this:

Preview the page and check if the gallery shows up fine. Try clicking the images in the preview. What happens depends on the gallery settings: you can change this in the sidebar if the gallery is selected: find the “Link To” setting.

To add the lightbox, simply add the code below to the page or post (in a Custom HTML block).

<script src="https://home.et.utwente.nl/slootenvanf/div/strip/js/strip.pkgd.min.js"></script>
<link rel='stylesheet' id='strip-style-css' href='https://home.et.utwente.nl/slootenvanf/div/strip/css/strip.css' type='text/css' media='all' />
<script>
jQuery(function($){
  $(window).on('load', function() { // document is fully loaded
    $('.entry-content figure img').each(function() { // new wp5 style way of image inclusion
    url = $(this).attr("src");
    extension = url.substr( (url.lastIndexOf('.') +1) ).toLowerCase();
    if (extension=="jpg"||extension=="png") { // if link points to an image, add strip lightbox:
        $(this).parent().addClass("strip");
        $(this).parent().attr("data-strip-group","gallery-group");
        $(this).parent().attr("href",url);
        if ($(this).attr("alt").length>0) $(this).parent().attr("data-strip-caption", $(this).attr("alt") );
    }
    });
  });
});
</script>

This example code will load the Strip lightbox, its CSS and the jQuery code which scans the page for an image gallery and add the lightbox to the images in the gallery.

Using the same way of adding code you can add any lightbox to a gallery. For instance, it will also work with FancyBox.

A more universal way is to add the code to your theme (eg. in the footer). It will then work on any page on your site which contains a gallery.

More info: