0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Docker環境でゼロから作る WordPress プラグイン入門

Posted at

Docker環境でゼロから作る WordPress プラグイン入門

はじめに

Docker Compose で構築した WordPress 開発環境に、自作プラグインを実装しました。投稿本文の末尾にメッセージを差し込み、管理画面からテキストを変更でき、ショートコードで再利用までこなせる「ちょっと便利」な機能です。この記事では、環境構築からプラグインの作り方、そして忘れがちなプラグインヘッダーの設定までをまとめます。

ゴールとできること

  • 投稿/固定ページ本文の末尾にメッセージを自動追記
  • 管理画面に独自メニュー「独自プラグイン設定」を追加
  • 入力したテキストを [my_info] ショートコードとして出力
  • WordPress 公式形式のプラグインヘッダーを揃えて管理画面で正しく認識させる

動作環境

README.MD と .env で管理している Docker ベースの開発環境です。

コンポーネント バージョン
WordPress 6.11
PHP 7.4.3
MySQL 5.7
nginx 1.20
Node.js 16.x

主要なポート設定(.env より):

  • WEB_PORT=8000 : WordPress 本体 (http://localhost:8000)
  • MYSQL_PORT=3310 : MySQL
  • MYSQL_DATABASE=test-db, MYSQL_USER=user, MYSQL_PASSWORD=passwd

起動・停止コマンド(Makefile 経由):

make up       # コンテナ起動
make down     # コンテナ停止
make build    # イメージ再ビルド(起動は別途 make up)
make web      # web コンテナに接続
make app      # php コンテナに接続

プロジェクト構成(抜粋)

wordpress/
└─ wp-content/
   └─ plugins/
      ├─ index.php
      └─ my-first-plugin/
         └─ my-first-plugin.php

記事の中心となるファイルは wordpress/wp-content/plugins/my-first-plugin/my-first-plugin.php です。

プラグインコード徹底解説

1. プラグインヘッダーを定義する

WordPress でプラグインとして認識させるには、ファイル先頭にヘッダーコメントを入れる必要があります。今回は以下のように設定しました。

<?php
/**
 * Plugin Name:       My First Plugin
 * Description:       プラグイン作成してみました
 * Version:           1.0.0
 * Requires at least: 6.1
 * Requires PHP:      7.4
 * Author:            AutherName
 */
  • Plugin Name がないと管理画面にプラグインが出てこないので必須。

2. 投稿本文の末尾にメッセージを追加

add_filter('the_content', 'my_add_message_after_content');

function my_add_message_after_content($content) {
    if (is_singular() && in_the_loop() && is_main_query()) {
        $my_message = '<p style="border: 2px solid red; padding: 10px;">★プラグインからのメッセージです!★</p>';
        return $content . $my_message;
    }
    return $content;
}
  • the_content フィルターフックで本文にフック。
  • is_singular(), in_the_loop(), is_main_query() による条件で安全に限定。

3. 管理画面に独自メニューを追加

add_action('admin_menu', 'my_plugin_add_admin_menu');

function my_plugin_add_admin_menu() {
    add_menu_page(
        '独自プラグイン設定',
        '独自プラグイン設定',
        'manage_options',
        'my-first-plugin-settings',
        'my_plugin_settings_page_html',
        'dashicons-admin-generic',
        10
    );
}
  • 独自メニューから設定ページを開けるように構成。

4. 設定画面の HTML と設定値登録

add_action('admin_init', 'my_plugin_register_settings');

function my_plugin_register_settings() {
    register_setting(
        'my-plugin-settings-group',
        'my_plugin_custom_text',
        'sanitize_text_field'
    );
}

function my_plugin_settings_page_html() {
    if (! current_user_can('manage_options')) {
        return;
    }
    ?>
    <div class="wrap">
        <h1><?php echo esc_html(get_admin_page_title()); ?></h1>
        <p>ここで設定したテキストを、ショートコード <code>[my_info]</code> で呼び出せます。</p>
        <form action="options.php" method="post">
            <?php settings_fields('my-plugin-settings-group'); ?>
            <table class="form-table">
                <tr>
                    <th scope="row"><label for="my_plugin_custom_text">表示したいテキスト</label></th>
                    <td>
                        <input type="text"
                               id="my_plugin_custom_text"
                               name="my_plugin_custom_text"
                               value="<?php echo esc_attr(get_option('my_plugin_custom_text')); ?>"
                               class="regular-text" />
                        <p class="description">例: 03-XXXX-XXXX や 「セール開催中!」 など</p>
                    </td>
                </tr>
            </table>
            <?php submit_button('設定を保存'); ?>
        </form>
    </div>
    <?php
}
  • register_setting で WordPress のオプション API と連携。
  • 入力値は sanitize_text_field でサニタイズ。

5. 設定値をショートコードとして出力

add_shortcode('my_info', 'my_info_shortcode_function');

function my_info_shortcode_function() {
    $saved_text = get_option('my_plugin_custom_text');
    if (! empty($saved_text)) {
        return esc_html($saved_text);
    }
    return '';
}
  • [my_info] を本文に差し込むだけで保存テキストを表示。

実際の操作手順

  1. make up でコンテナを起動し、http://localhost:8000 にアクセス。
  2. WordPress 管理画面から「プラグイン > プラグイン一覧」で「My First Plugin」を有効化。
  3. 左メニューに追加される「独自プラグイン設定」でテキストを入力・保存。
  4. 投稿本文末尾に赤枠メッセージが自動追加されるのを確認。
  5. 投稿/固定ページに [my_info] ショートコードを挿入すると設定テキストを任意位置に出力可能。

まとめと今後の拡張アイデア

  • プラグインヘッダーを忘れると管理画面に表示されないので最優先で準備すること。
  • フック、設定 API、ショートコードの流れを理解できるミニプラグインになった。
  • languages/ 配下に翻訳ファイルを用意したり、ブロックエディタ対応のブロック化、REST API 連携など発展ネタ多数。

Docker環境ならすぐに試せるので、ヘッダー定義も含めてぜひ手を動かしてみてください!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?