WordPress 画像クリックで拡大する(モーダルライトボックス効果)

Last Updated:2023年11月09日| | 7のコメント

Newspaper 一部のテーマでは、本文内の画像をクリックすると画像を拡大して表示するモーダルライトボックス画像機能を有効/無効にする機能を提供しています。 これらの機能が提供されていない場合は、モーダルプラグインを使用できます。 この記事では、JavaScriptを使用して WordPress ブログの本文に挿入された画像をクリックしたときに画像が拡大表示されるようにする方法を見てみましょう。

2023年11月9日アップデート: WordPressがバージョン6.4にアップデートされ、画像ブロックとギャラリーブロックに画像ライトボックスオプションが追加されました。 画像のライトボックススタイルを調整する方法は、以下の記事で確認できます。

WordPress 画像クリックで拡大する(モーダルライトボックス効果)

テーマでモーダル画像機能を提供していない場合 FooBoxのようなライトボックス&モーダルポップアップ WordPress プラグイン(Lightbox & Modal Popup WordPress Plugin)をインストールして、必要に応じて機能していることを確認してください。

この記事では、ブロックエディタ(Gutenberg)の画像ブロックを使用して、挿入した画像をユーザーがクリックしたときにモーダルポップアップとして表示されるようにする方法を見てみましょう。

ユーザーが画像をクリックしたときに画像にリンクがある場合はそのリンクに移動し、リンクがない場合はモーダルポップアップとして表示する場合を考えてみましょう。

ブロックエディタで画像ブロックを挿入すると、XNUMXつの形式でHTMLコードが追加されるようです。

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

- または -

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

私のブログは現在、XNUMX番目の形式で画像ブロックが追加されています。 同じ GeneratePress テーマを使用している場合でも、一部のサイトでは最初の形式で画像が挿入されることもあるようです。

上記のように画像ブロックが追加されている場合は、次のJavaScriptコードを使用して、リンクされていない画像を訪問者がクリックしたときにモーダルポップアップとして表示することができます。

/*
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>

上記のコードを適用すると、デスクトップデバイス(768ピクセル以上の解像度)でのみモーダルポップアップが機能します。 モバイルデバイスを含むすべてのデバイスに適用するには、上記のコードから 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");

JavaScriptを追加する方法

上記のJavaScriptコードは、次の記事で紹介する方法でロードできます。

上記の方法でロードするのが望ましいですが、この方法が難しい場合 WPコードをインストールしてフーター領域に追加することもできます。

GeneratePress テーマを使用している場合は、フック(HooK)を使用して、すべての記事にジャスコードをフッタ領域にロードすることができます。

  • フック: wp_footer
  • Display Rules » Location: <文 - All 文>を指定

参照


7のコメント

コメント

  1. XNUMXつの画像はモーダルポップアップが機能しますが、ギャラリーで編集してXNUMXつ以上の画像をXNUMXつにすると、モーダルポップアップが実行されず、PNGファイルがそのまま開きます。 設定する方法はありますか?

    応答
    • 画像にリンクがあると、モーダルは機能せずにリンクが開きます。
      現在のコードで次の部分を修正する必要があるようです。

      - 画像が小さいサイズ(サムネイル)で追加された場合、モーダルでは全体画像(原画像)が表示されるように修正
      - 画像リンクに対応するメディアファイルがリンクにかかってもモーダルとして機能するようにコードを修正

      時間が経つにつれて、上記の部分をどのように適用するかを考えてみましょう。

      応答
    • ギャラリーにXNUMXつの画像を入れてテストしてみると、うまく動作するようです。
      画像にリンクが適用されている場合、モーダル画像としては機能しません。

      スクリプトコードは、サムネイルサイズの画像に対しても機能するように更新しました。

      応答
    • こんにちは、ヒョンウォン。 本文の内容を修正しました。 「上記のコードが機能しない場合」を参照してください。 一箇所を修正すると機能します。

      応答
      • ワード様やってみるとモーダル適用になりましたありがとうございます。
        ただし、イメージが元のサイズと同じように浮かぶ状況です。

        画像を少し拡大したいのですが、どのコードを修正すればよいでしょうか。

      • 画像を挿入するときに「最大サイズ」に設定すると、モーダルポップアップでも最大サイズで表示されます。
        挿入した画像が最大サイズでない場合は、画像名が「image_name-300x184.jpg」のようになっている可能性があります。 そのような場合は、画像名の後ろの画像サイズ部分(「-300x184」)を削除するように上記のコードを変更する必要があります。

        この部分については、今後の適用が可能であれば修正されたコードで更新します。