WordPressの記事をまるごとモーダルウィンドウにしてみる

WordPressにモーダルウィンドウを実装する方法は色々ありますが、今回は記事をまるごとモーダルウィンドウに表示する方法をやってみようと思います。

なお、モーダルウィンドウ自体には、jQueryのプラグイン 「Remodal」 を使用します。簡単な設定でモーダルウィンドウを実装できます。その他のモーダルウィンドウのプラグインでも応用可能です。

目次

Remodalをダウンロードする

まず、 「Remodal」 のサイトから必要なファイルを入手します。

公式サイトの「Download」をクリックして、GitHubのページから「Source code」をクリックして圧縮ファイルをダウンロードします。

解凍後の「dist」フォルダ内の
remodal.css
remodal-default-theme.css
remodal.min.js
が必要なファイルです。

Remodalを読み込む

次に、先ほど入手したファイルをWordPressに読み込む設定を記述します。

ファイルを適当な所に置いて、functions.phpに読み込みの設定を記述します。

なるべく子テーマを作成して設定した方がいいと思います。
 参考: Child Themes

例: 子テーマの functions.php

function my_child_theme_enqueue_scripts() {
    wp_enqueue_style( 'remodal-style', get_stylesheet_directory_uri() . '/css/remodal.css', array() );
    wp_enqueue_style( 'remodal-default-style', get_stylesheet_directory_uri() . '/css/remodal-default-theme.css', array() );
    wp_enqueue_script( 'remodal-script', get_stylesheet_directory_uri() . '/js/remodal.min.js', array('jquery'), '', true );
}
add_action( 'wp_enqueue_scripts', 'my_child_theme_enqueue_scripts' );

ショートコードを作成する

色々な場所に表示できるようにショートコードにしておきます。
今回は固定ページをまるごと表示できるようにします。

例: モーダルウィンドウのショートコード

<?php
function get_my_remodal() {
    $args = array(
        'posts_per_page'  => 1,
        'post_type'       => 'page', // 固定ページ
        'name'            => 'sample-remodal', // URLスラッグ
        'post_status'     => 'private', // 非公開にした場合
    );
    $myremodal = get_posts( $args ); // 記事を取得
    if ( $myremodal ) {
        foreach ( $myremodal as $post ) {
            setup_postdata( $post );
            $modal_content = $post->post_content;
            wp_reset_postdata();
        }
    }

    ob_start();
    ?>
    <a href="#my-remodal" class="modal-btn">モーダルウィンドウ</a>
    <div class="remodal" data-remodal-id="my-remodal">
        <button data-remodal-action="close" class="remodal-close"></button>
        <div>
            <?php echo $modal_content; ?>
        </div>
    </div>
    <?php
    return ob_get_clean();
}
add_shortcode( 'my_remodal', 'get_my_remodal' );

前半は、モーダルウィンドウとして表示する固定ページを取得する部分です。

後半は、ob_start()でモーダルウィンドウのHTML部分を出力します。
モーダルウィンドウのHTMLは、 aタグの href属性と divタグの data-remodal-idの値を同じにします。
その他のクラスや属性値も上記のまま記述するとデフォルトのスタイルや機能が利用できます。

詳しい Remodalの使用方法やオプションは、
https://github.com/VodkaBears/Remodal#remodal
に載っています。

モーダルウィンドウを編集する

固定ページを作成して、モーダルウィンドウを編集します。

固定ページのURLスラッグは、ショートコードで設定したものにします。
ページに直接アクセスしてほしくない場合は、ショートコードの設定で「post_status」を「private」にして、表示状態を「非公開」にしておきます。

ショートコードを書く

あとは、ショードコードを記事内やウィジェットに記述すればモーダルウィンドウを表示できます。

以下、サンプルです。

モーダルウィンドウ

モーダルウィンドウのサンプル

サンプル

まとめ

この方法は、エディタをフル活用して編集できる他、モーダルウィンドウごとに個別に管理できるメリットがあると思います。

コメントを残す

メールアドレスが公開されることはありません。
* が付いている欄は必須項目です。