Lightweight Image Lightbox
Opens linked images in post content in a full-screen overlay instead of a new page, with keyboard and click-to-close support and no external library.
Opens WPIDE on
Code
<div id="wpide-lightbox" hidden role="dialog" aria-modal="true" aria-label="Image viewer" style="position:fixed;inset:0;z-index:100000;display:flex;align-items:center;justify-content:center;padding:24px;background:rgba(0,0,0,.88);cursor:zoom-out;">
<img alt="" style="max-width:100%;max-height:100%;box-shadow:0 8px 40px rgba(0,0,0,.5);">
</div>
<script>
(function () {
var box = document.getElementById('wpide-lightbox');
if (!box) { return; }
var img = box.querySelector('img'), last = null;
function close() { box.hidden = true; img.removeAttribute('src'); if (last) { last.focus(); } }
document.addEventListener('click', function (e) {
var link = e.target.closest ? e.target.closest('a[href]') : null;
if (!link || !link.querySelector('img') || !/\.(jpe?g|png|gif|webp|avif)(\?.*)?$/i.test(link.getAttribute('href'))) { return; }
e.preventDefault();
last = link;
img.src = link.href;
img.alt = (link.querySelector('img').alt || '');
box.hidden = false;
box.focus();
});
box.setAttribute('tabindex', '-1');
box.addEventListener('click', close);
document.addEventListener('keydown', function (e) { if (e.key === 'Escape' && !box.hidden) { close(); } });
})();
</script>
Notes
Works on images that link to their media file (set "Link to: Media File" in the image block). Press Escape or click anywhere to close.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.