ヘルプ項目を新規作成できるようにする – WordPressプラグインの作成 15

投稿者: | 2018年3月11日

[新規作成]ボタンをクリックして、ヘルプ項目を新規作成できるようにします。
[新規作成]ボタンは送信(submit)ボタンにしているので、これがクリックされると、POST送信が行われます。POSTで送信されてきたデータを確認し、新規作成などの処理を行う必要があります。

POSTデータを検証する

POST送信のデータを検証する関数を、Fow_OnlineHelp_Admin クラスに追加します。関数名を validate_post にします。
まずは、関数で使用するフィールドを、以下のように Fow_OnlineHelp_Admin クラスに追加しましょう(21行目)。

    /**
     * フィールド
     */
    private $form = '';

validation_post 関数を追加します。コードは以下のとおりです。

    /**
     * POSTで受け取ったデータを検証する
     */
    public function validate_post()
    {
        // submitボタンの種類
        $command = filter_input(INPUT_POST, 'submit');
        // どのフォーム(ビュー)から送られてきたか
        $this->form = filter_input(INPUT_POST, 'form');
        // フォームごとのバリデーションに分岐
        switch ($this->form) {
            case 'top':
                $this->validate_top($command);
                break;
            case 'edit':
                $this->validate_edit($command);
                break;
            default:
                $this->form = '';
                break;
        }
    }

top.php の修正

どのフォーム(ビュー)から送信されてきたかを判断するため、フォームに隠し属性のデータを追加します。views/top.php ファイルを以下のように修正します(11行目)。

    <form method="POST" action="">
        <input type="hidden" name="form" value="top">
        <!--コマンドバー-->
        <div class="tablenav top">

validate_top 関数の追加

オンラインヘルプ管理ページのトップ画面から送信されたPOSTデータは、validate_top 関数で検証することになります。Fow_OnlineHelp_Admin クラスに、validate_top 関数を追加します。

    /**
     * トップ画面のバリデーション
     * @param   string  $command    submitボタンの値
     */
    public function validate_top($command)
    {
        // 押されたボタンによって分岐
        switch ($command) {
            case 'new':
                $this->form = 'new';
                break;
        }
    }

submitボタンの値が new となっているか確認します。そうであれば、form フィールドに new という文字列を設定しておきます。

print_admin_page 関数の修正

管理画面を実際に出力しているのは、print_admin_page 関数となります。print_admin_page 関数で form フィールドの値を確認し、出力するページを切り替えます。以下のように修正します(68-95行目)。

    /**
     * 管理ページを出力する
     */
    public function print_admin_page()
    {
        if (!current_user_can('manage_options')) {
            wp_die(__('管理ページへのアクセス権限がありません。'));
        }

        global $onlinehelp_db;
        global $onlinehelp_lib;

        // データの取得
        $products = $onlinehelp_db->fetch_products();
        $categories = $onlinehelp_db->fetch_categories();

        // formの値によって表示するビューを変える
        switch ($this->form) {
            case 'new':
                // 編集データの作成
                $help = $onlinehelp_lib->get_empty_help();
                require_once FOW_OH_PLUGIN_DIR . '/views/edit.php';
                break;

            default:
                $items = $onlinehelp_db->fetch_helps(0, 0, $this->settings['sorted'], $this->settings['sorted-order']);

                // データの設定
                $pagination = $this->settings['pagination'];
                $pagination['max'] = $onlinehelp_lib->get_page_max(count($items), $this->settings['rows']);

                $this->settings['sortlink'] = $onlinehelp_lib->format_url(['sort']);
                $this->settings['itemlink'] = $onlinehelp_lib->format_url(['item', 'sort']);
                $this->settings['row_begin'] = ($pagination['current'] - 1) * $this->settings['rows'];
                $this->settings['row_end'] = $this->settings['row_begin'] + $this->settings['rows'] - 1;
                if ($this->settings['row_end'] >= count($items)) {
                    $this->settings['row_end'] = count($items) - 1;
                }

                $this->settings['pagination'] = $pagination;

                // ビューの読み込み
                require_once FOW_OH_PLUGIN_DIR . '/views/top.php';
        }
    }

get_empty_help 関数の追加

新規作成データを取得できるよう、Fow_OnlineHelp_Lib クラスに get_empty_help 関数を追加します。コードは以下のとおりです。

    /**
     * 空のヘルプ項目データを返す
     * @return  array   ヘルプ項目データ
     */
    function get_empty_help()
    {
        $result = [
            'help_id' => 0,
            'title' => '',
            'helpbody' => '',
            'tags' => '',
            'relations' => '',
            'product_id' => '',
            'category_id' => '',
            'created_at' => '',
        ];

        return $result;
    }

ビューの作成

新規作成用の画面(ビュー)を作成します。なお、このビューは新規作成のほか、既存データの編集にも使用する予定です。
ビューのファイルは views フォルダー内に、edit.php というファイル名で作成します。内容は以下のとおりです。

<div class="wrap">
    <h2>ヘルプ項目の作成・編集</h2>
    <form action="" method="POST">
        <input type="hidden" name="form" value="edit">
        <input type="hidden" name="help_id" value="<?=$help['help_id']?>">
        <table class="form-table">
            <tr>
                <th scope="row"><label for="input-title">タイトル</label></th>
                <td>
                    <input type="text" name="title" id="input-title" class="regular-text" value="<?=esc_html($help['title'])?>">
                </td>
            </tr>
            <tr>
                <th scope="row"><label for="input-body">ヘルプ本文</label></th>
                <td>
                    <div class="postarea wp-editor-expand">
                        <div class="wp-editor-container">
                            <textarea class="wp-editor-area" style="width: 100%; height: 300px;" autocomplete="off" name="helpbody"><?=esc_textarea($help['helpbody'])?></textarea>
                        </div>
                    </div>
                </td>
            </tr>
            <tr>
                <th scope="row"><label for="input-tags">タグ</label></th>
                <td>
                    <input type="text" name="tags" id="input-tags" class="regular-text" value="<?=esc_html($help['tags'])?>">
                    <p class="description">このヘルプ項目に付けるタグを指定します。<br />複数のタグはコンマで区切ります。</p>
                </td>
            </tr>
            <tr>
                <th scope="row"><label for="input-relations">関連タグ</label></th>
                <td>
                    <input type="text" id="input-relations" name="relations" class="regular-text" value="<?=esc_html($help['relations'])?>">
                    <p class="description">この項目に関連する項目のタグを指定します。<br />複数のタグはコンマで区切ります。</p>
                </td>
            </tr>
            <tr>
                <th scope="row"><label for="input-product">製品</label></th>
                <td>
                    <span>
                        <select id="input-product" name="product_id">
                            <option value="0">選択してください</option>
                            <?php foreach ($products as $_product): ?>
                                <option value="<?=esc_attr($_product->product_id)?>"><?=esc_html($_product->prod_name)?></option>
                            <?php endforeach;?>
                        </select>
                    </span>
                    <span>
                        <input type="text" name="new_product" class="regular-text" placeholder="登録する製品名">
                    </span>
                    <span>
                        <button type="submit" name="submit" class="button button-secondary" value="add-product">製品の登録</button>
                    </span>
                </td>
            </tr>
            <tr>
                <th scope="row"><label for="input-category">カテゴリー</label></th>
                <td>
                    <span>
                        <select id="input-category" name="cat_id">
                            <option value="0">選択してください</option>
                            <?php foreach ($categories as $_category): ?>
                                <option value="<?=esc_attr($_category->cat_id)?>"><?=esc_html($_category->cat_name)?></option>
                            <?php endforeach;?>
                        </select>
                    </span>
                    <span>
                        <input type="text" name="new_category" class="regular-text" placeholder="登録するカテゴリー">
                    </span>
                    <span>
                        <button type="submit" name="submit" class="button button-secondary" value="add-category">カテゴリー登録</button>
                    </span>
                </td>
            </tr>
        </table>
        <p class="submit">
            <button type="submit" class="button button-primary" name="submit" value="save">保存する</button>
        </p>
    </form>
</div>

validate_post関数の呼び出し

作成した validate_post 関数を、onlinehelp_main.php から呼び出します。
onlinehelp_main.php を以下のように編集します(26行目を追加)。

/**
 * クラスのインスタンスを生成する
 */
global $onlinehelp_db;
global $onlinehelp_lib;
$onlinehelp_db = new Fow_OnlineHelp_DB();
$onlinehelp_lib = new Fow_OnlineHelp_Lib();
$onlinehelp_admin = new Fow_OnlineHelp_Admin();
$onlinehelp_admin->validate_post();
$onlinehelp_admin->validate_get();

動作テスト

管理画面で[新規作成]ボタンをクリックし、編集ページが表示されるか確認しましょう。

ヘルプ項目を新規作成できるようにする – WordPressプラグインの作成 15」への1件のフィードバック

  1. kino_3240 投稿作成者

    作成した validate_post 関数を呼び出す部分が抜けていましたので、これを追加しました。

    返信

コメントを残す

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

日本語が含まれない投稿は無視されますのでご注意ください。(スパム対策)