워드프레스 이미지 클릭 시 확대하기 (모달 라이트박스 효과)

Last Updated: 2023년 11월 09일 | | 7개 댓글

뉴스페이퍼 등 일부 테마에서는 본문 내의 이미지를 클릭 시 이미지를 확대하여 표시하는 모달 라이트박스 이미지 기능을 활성화/비활성화할 수 있는 기능을 제공합니다. 이런 기능이 제공되지 않는 경우 모달 플러그인을 사용할 수 있습니다. 이 글에서는 자바스크립트를 사용하여 워드프레스 블로그 글 본문에 삽입된 이미지를 클릭할 경우 이미지가 확대되어 표시되도록 방법을 살펴보겠습니다.

2023년 11월 9일 업데이트: 워드프레스가 6.4 버전으로 업데이트되면서 이미지 블록과 갤러리 블록에서 이미지 라이트박스 옵션이 추가되었습니다. 이미지 라이트박스 스타일을 조정하는 방법을 아래 글에서 확인할 수 있습니다.

워드프레스 이미지 클릭 시 확대하기 (모달 라이트박스 효과)

테마에서 모달 이미지 기능을 제공하지 않는 경우 FooBox와 같은 라이트박스 & 모달 팝업 워드프레스 플러그인(Lightbox & Modal Popup WordPress Plugin)을 설치하여 원하는 대로 작동하는지 체크해 볼 수 있습니다.

이 글에서는 블록 에디터(구텐베르크)의 이미지 블록을 사용하여 삽입한 이미지를 사용자가 클릭할 경우 모달 팝업으로 표시되도록 하는 방법을 살펴보겠습니다.

사용자가 이미지를 클릭 시 이미지에 링크가 걸려 있으면 해당 링크로 이동하고 링크가 없으면 모달 팝업으로 표시하는 경우를 생각해보겠습니다.

블록 에디터에서 이미지 블록을 삽입하면 세 가지 형식으로 HTML 코드가 추가되는 것 같습니다.

<figure class="wp-block-image size-large"><img ...></figure>

- 또는 -

<div class="wp-block-image"><figure ...><img ...></figure></div>

제 블로그는 현재 두 번째 형식으로 이미지 블럭이 추가되어 있습니다. 동일한 GeneratePress 테마를 사용하는 경우에도 어떤 사이트에서는 첫 번째 형식으로 이미지가 삽입되기도 하는 것 같습니다.

위와 같이 이미지 블록이 추가되어 있는 경우, 다음과 같은 자바스크립트 코드를 사용하여 링크가 걸리지 않은 이미지를 방문자가 클릭하면 모달 팝업으로 표시되도록 할 수 있습니다.

/*
This script enhances the image viewing experience within WordPress posts by enabling a modal popup functionality. 
When a user clicks on an image that isn't contained within a hyperlink, the image is displayed in a full-screen 
overlay, or 'modal', thus focusing the user's attention solely on the image. The modal can be closed either by 
clicking on the 'X' button positioned in the top right corner, or by clicking outside the image. This provides 
an engaging and user-friendly way to view images in WordPress posts.
*/

<script>
// get all the images
var images = document.querySelectorAll(".wp-block-image img, .wp-block-image figure img");

// iterate over each image
for(let img of images) {
    // check if parent is not a link and device is not mobile
    if(img.parentElement.tagName !== 'A' && window.matchMedia("(min-width: 768px)").matches) {
        // create modal div
        var modal = document.createElement("div");
        modal.style.display = "none";
        modal.style.position = "fixed";
        modal.style.zIndex = "1";
        modal.style.paddingTop = "100px";
        modal.style.left = "0";
        modal.style.top = "0";
        modal.style.width = "100%";
        modal.style.height = "100%";
        modal.style.overflow = "auto";
        modal.style.backgroundColor = "rgba(0,0,0,0.9)";
        modal.id = "myModal";

        // create close button
        var closeBtn = document.createElement("span");
        closeBtn.innerHTML = "&times;";
        closeBtn.style.position = "absolute";
        closeBtn.style.top = "15px";
        closeBtn.style.right = "35px";
        closeBtn.style.color = "#f1f1f1";
        closeBtn.style.fontSize = "40px";
        closeBtn.style.fontWeight = "bold";
        closeBtn.style.transition = "0.3s";
        closeBtn.style.cursor = "pointer";
        closeBtn.onclick = function() { 
            modal.style.display = "none";
        };

        // create modal img
        var modalImg = document.createElement("img");
        modalImg.style.margin = "auto";
        modalImg.style.display = "block";
        modalImg.style.width = "80%";
        modalImg.style.maxWidth = "700px";
        modalImg.id = "img01";

        // append elements to modal
        modal.appendChild(closeBtn);
        modal.appendChild(modalImg);

        // append modal to body
        document.body.appendChild(modal);

        // add click event to the image
        img.onclick = function() {
            modal.style.display = "block";
            modalImg.src = this.src;
        }

        // add close event to the modal
        window.onclick = function(event) {
            if (event.target == modal) {
                modal.style.display = "none";
            }
        }
    }
}
</script>

위의 코드를 적용하면 데스크탑 기기(768px 이상의 해상도)에서만 모달 팝업이 작동하게 됩니다. 모바일 기기를 비롯한 모든 기기에 적용하려면 위의 코드에서 window.matchMedia("(min-width: 768px)").matches 부분을 삭제하면 됩니다.

스크립트 업데이트:

이미지가 Yoast-SEO-Update-768x378.jpg와 같이 전체 크기가 아닌 썸네일 크기로 삽입되어 있는 경우, 상기 코드를 사용할 경우 이미지를 클릭하면 썸네일이 모달로 표시됩니다. 썸네일 크기로 이미지가 삽입되어도 모달 팝업에서 전체 이미지 크기로 표시되도록 스크립트를 수정했습니다.

// get all the images
var images = document.querySelectorAll(".wp-block-image img, .wp-block-image figure img");

// iterate over each image
for(let img of images) {
    // check if parent is not a link and device is not mobile
    if(img.parentElement.tagName !== 'A' && window.matchMedia("(min-width: 768px)").matches) {
        // create modal div
        var modal = document.createElement("div");
        modal.style.display = "none";
        modal.style.position = "fixed";
        modal.style.zIndex = "1";
        modal.style.paddingTop = "100px";
        modal.style.left = "0";
        modal.style.top = "0";
        modal.style.width = "100%";
        modal.style.height = "100%";
        modal.style.overflow = "auto";
        modal.style.backgroundColor = "rgba(0,0,0,0.9)";
        modal.id = "myModal";

        // create close button
        var closeBtn = document.createElement("span");
        closeBtn.innerHTML = "&times;";
        closeBtn.style.position = "absolute";
        closeBtn.style.top = "15px";
        closeBtn.style.right = "35px";
        closeBtn.style.color = "#f1f1f1";
        closeBtn.style.fontSize = "40px";
        closeBtn.style.fontWeight = "bold";
        closeBtn.style.transition = "0.3s";
        closeBtn.style.cursor = "pointer";
        closeBtn.onclick = function() { 
            modal.style.display = "none";
        };

        // create modal img
        var modalImg = document.createElement("img");
        modalImg.style.margin = "auto";
        modalImg.style.display = "block";
        modalImg.style.width = "80%";
        modalImg.style.maxWidth = "700px";
        modalImg.id = "img01";

        // append elements to modal
        modal.appendChild(closeBtn);
        modal.appendChild(modalImg);

        // append modal to body
        document.body.appendChild(modal);

        // add click event to the image
        img.onclick = function() {
            modal.style.display = "block";
            modalImg.src = this.src.replace(/-\d+x\d+(?=.jpg$|.jpeg$|.png$|.webp$)/, '');
        }

        // add close event to the modal
        window.onclick = function(event) {
            if (event.target == modal) {
                modal.style.display = "none";
            }
        }
    }
}

모달 팝업 예시:

모달 이미지 팝업 시 이미지 외부의 영역을 마우스로 클릭하거나 닫기 버튼(X 버튼)을 누르면 팝업이 사라집니다.

상기 코드가 작동하지 않을 경우

위의 코드가 작동하지 않을 경우 이미지 부분의 HTML 태그를 확인해보시기 바랍니다. 예를 들어, 다음과 같은 HTML 포맷으로 이미지가 삽입되는 경우도 있는 것 같습니다.

<figure class="wp-caption"><img...></figure>

이 경우 상기 자스 코드의 다음 부분을

var images = document.querySelectorAll(".wp-block-image img, .wp-block-image figure img");

다음과 같이 수정하여 테스트해 보시기 바랍니다.

var images = document.querySelectorAll(".wp-block-image img, .wp-block-image figure img, .wp-caption img");

자바스크립트를 추가하는 방법

상기 자바스크립트 코드를 다음 글에서 소개하는 방법으로 로드할 수 있습니다.

위의 방법 방법으로 로드하는 것이 바람직하지만 이 방법이 어려운 경우 WPCode를 설치하고 푸터(Footer) 영역에 추가하는 것도 가능합니다.

GeneratePress 테마를 사용하는 경우 훅(HooK)을 사용하여 모든 글에 자스 코드를 푸터 영역에 로드되도록 할 수 있습니다.

  • Hook: wp_footer
  • Display Rules » Location: <글 - All 글> 지정

참고


7 개 댓글

Leave a Comment

  1. 한개의 이미지는 모달 팝업이 작동하지만, 갤러리로 편집하여 두개 이상의 이미지를 하나로 만들면 모달 팝업이 실행되지 않고 PNG파일이 그대로 열립니다. 설정하는 방법이 있나요?

    응답
    • 이미지에 링크가 걸려있으면 모달은 작동하지 않고 링크가 열립니다.
      현재 코드에서 다음 부분을 수정해야 할 것 같습니다.

      - 이미지가 작은 크기(썸네일)로 추가된 경우 모달에서는 전체 이미지(원본 이미지)가 표시되도록 수정
      - 이미지 링크에 해당 미디어 파일이 링크로 걸린 경우에도 모달로 작동하도록 코드 수정

      시간이 될 때 위의 부분을 어떻게 적용할지 고민해보겠습니다.

      응답
    • 갤러리에 두 개의 이미지를 넣어서 테스트해보니 잘 작동하는 것 같습니다.
      이미지에 링크가 적용되어 있으면 모달 이미지로 작동하지 않습니다.

      스크립트 코드는 썸네일 크기의 이미지에 대하여도 작동하도록 업데이트했습니다.

      응답
    • 안녕하세요, 현원님. 본문의 내용을 수정했습니다. "상기 코드가 작동하지 않을 경우" 섹션을 참고해보세요. 한 군데를 수정하시면 작동할 것입니다.

      응답
      • 워드님 해보니 모달 적용이 되었습니다 감사합니다.
        다만, 이미지가 원래의 크기랑 똑같이 뜨는 상황입니다.

        이미지를 좀 확대하고 싶은데 어느 코드를 수정하면 되겠는지요..

      • 이미지를 삽입하실 때 "최대 크기"로 설정할 경우에는 모달 팝업에서도 최대 크기로 표시될 것입니다.
        만약 삽입된 이미지가 최대 크기가 아닌 경우 이미지 이름이 "이미지_이름-300x184.jpg"와 같이 되어 있을 수 있습니다. 그런 경우에는 이미지 이름에서 뒤의 이미지 크기 부분("-300x184")을 삭제하도록 위의 코드를 수정해야 할 것입니다.

        이 부분에 대해서는 추후에 적용이 가능하면 수정된 코드로 업데이트하겠습니다.