Task Description
When user clicks an image within the entry, the image will be opened into a lightbox, so that it is bigger to see. This is useful in case the image has some small details that you would like users to see better.
Steps:
- Add a lightbox js library to the footer scripts (in this post, I choose Lity, you can use the library of your choice, the principle is the same).
- Use JavaScript to find all images within the post, add a click event listener and trigger Lity to open a lightbox based on that.
So this sounds a bit weird and do not feel very WordPress-way, right? Anyway, it works for me.
Using wp_enqueue_script and wp_enqueue_style, we can enqueue custom scripts to WordPress. And in this case, I will add it to the footer. So, in your child theme’s functions.php:
// Add lity library to WordPress
add_action('wp_footer', 'ak_add_lity');
function ak_add_lity() {
if ( !is_singular('post')) return;
wp_enqueue_script ( 'lightbox', 'https://cdnjs.cloudflare.com/ajax/libs/lity/2.4.1/lity.min.js' );
wp_enqueue_style ( 'lightbox', 'https://cdnjs.cloudflare.com/ajax/libs/lity/2.4.1/lity.css' );
}
Notice: The wp_footer is the hook for general WordPress theme, with Genesis, you have to use genesis_before_footer:
Attach Lightbox Opener to a Click Event of Each Image
Here, we can inject some JavaScript code, which do the following tasks:
- First, get all the images within the entry-content class
- Second, add a click event listener to each image in the images array, to open a lity box
Sounds straightforward, right? Here is how to do it in code.
// Open each image in a lightbox
add_action('wp_footer', 'ak_add_lightbox_to_image');
function ak_add_lightbox_to_image() {
?>
<script>
const ENTRY_CONTENT = document.querySelector('.entry-content');
const ALL_IMAGES = ENTRY_CONTENT.getElementsByTagName('img');
for (let image of ALL_IMAGES) {
image.addEventListener('click', () => {
lity(image.src);
})
}
</script>
<?php
}
Similarly to the case above, for Genesis user, you need to use genesis_entry_footer hook instead of wp_footer.
Now you can go to any post and try the lightbox function. My website is currently doing that so it is a live demo. Check this out below with an image I took when travelling to Praha where they have street BBQ:

Last Step: Add a Pointer Cursor to Images
It is easier for visitors to know that there is something going on when they click an image by changing the mouse cursor into a pointer. Simply add this custom CSS to WordPress’s Customizer, or to your child theme style.css wherever you prefer:
.wp-block-image img {
cursor: pointer;
}
And if the lightbox does not open so nicely, you can add some custom CSS so that it looks better. If it already looks like what you need, you can stop reading here.
In my case of Genesis, I move the image in the lightbox to bottom aligned and resize it to 80%.
.lity-container {
vertical-align: bottom!important;
}
.lity-image img {
max-width: 80vw!important;
max-height: 80vh!important;
}