プラグインなしでCSSだけでポップアップ表示を追加する方法

Cocoonカスタマイズ集
この記事は約4分で読めます。
記事内に広告が含まれています。

はじめに

プラグイン「Popup Maker」などを使わずに、独自のショートコードを使用して、ボタンクリックでポップアップを表示します。

この記事では、その方法について説明します。

Popover APIを用い、JavaScriptを1行も書かずに、ブラウザの標準機能だけでポップアップの表示・非表示を実現しています。

完成イメージ

使用方法

以下にショートコードを示します。

[my_popup]
オプション
オプション説明値初期値
idパターンID(必須)
labelボタンテキスト

実装手順

  • ラベル
    パターンを作成

    パターンにポップアップ画面を作成・登録します。

  • ラベル
    PHPを追加

    以下のコードをfunctions.phpに追加します。

    // ショートコードを追加
    add_shortcode('my_popup', function ($atts) {
      $atts = shortcode_atts([
        'id'    => 0,
        'label' => '',
      ], $atts);
    
      $id = $atts['id'];
      $label = $atts['label'];
    
      if (empty($id) || $id == 0) {
        return '<p>パターンidが指定されていません。</p>';
      }
    
      $content = do_shortcode('[pattern id="' . $id . '"]');
    
      ob_start();
      ?>
      <div class="popup">
        <div class="aligncenter button-block">
          <button popovertarget="modal<?= esc_attr($id); ?>" class="btn btn-m btn-circle">
            <?= esc_html($label); ?>
          </button>
        </div>
        <dialog popover id="modal<?= esc_attr($id); ?>" class="popup__dialog">
          <div class="popup__content">
            <?= $content; ?>
          </div>
        </dialog>
      </div>
      <?php
      return ob_get_clean();
    });
    
    
    // フロント用JS・CSSを追加
    add_action('wp_enqueue_scripts', function () {
      ob_start();
      ?>
      .popup__dialog {
        animation: fade-in 0.3s;
        background-color: transparent;
        border: 0;
        margin: auto;
        padding: 10px;
        position: fixed;
        text-align: center;
    
        &::backdrop {
          animation: fade-in 0.3s;
          background-color: rgba(0, 0, 0, 0.5);
        }
    
        &:focus {
          outline: none;
        }
      }
    
      .popup__content {
        background-color: #fff;
        height: fit-content;
        padding: 10px;
        width: fit-content;
      }
    
      @keyframes fade-in {
        from {
          opacity: 0;
        }
    
        to {
          opacity: 1;
        }
      }
      <?php
    
      $handle = 'popup';
    
      wp_register_style($handle, false);
      wp_enqueue_style($handle);
      wp_add_inline_style($handle, ob_get_clean());
    });

さいごに

今回紹介した方法を使えば、プラグインを使わずに、ショートコードで簡単にボタンクリックによるポップアップ表示を実現できます。
<dialog>タグを使用することで、簡単にポップアップ表示が実装できます。

タイトルとURLをコピーしました