テーブルのソート – WordPressプラグインの作成 14

投稿者: | 2018年3月4日

設定ページのトップ画面を表示できるようになったので、各操作への対応を行います。まずはテーブル(表)のソートに対応します。
テーブルの列見出しには <a> タグを入れています。これをクリックすることで、テーブルをソートできるようにコーディングします。

validate_get関数の作成

ソート用の <a> タグのリンク先には、http://****/***?page=fow_online_admin&sort=1 のように、パラメーターを追加しています。このパラメーターをチェックする関数として、validate_get 関数を作成します。
validate_get 関数は、Fow_OnlineHelp_Admin クラスに追加します。内容は以下のとおりです。

    /**
     * GETで受け取ったデータを検証する
     */
    public function validate_get()
    {
        global $onlinehelp_lib;

        $sort = intval(filter_input(INPUT_GET, 'sort', FILTER_VALIDATE_INT, ['default' => 0, 'min_range' => 0, 'max_range' => 5]));
        $item = intval(filter_input(INPUT_GET, 'item', FILTER_VALIDATE_INT, ['default' => 0, 'min_range' => 0]));

        // ソート
        if ($sort !== 0) {
            $current_sort = intval($onlinehelp_lib->get_option('sort', 0));
            $current_sort_order = intval($onlinehelp_lib->get_option('sort_order', 0));

            if ($current_sort === $sort) {
                $current_sort_order = $current_sort_order === 1 ? 2 : 1;
            } else {
                $current_sort = $sort;
                $current_sort_order = 1;
            }

            $onlinehelp_lib->write_option('sort', $current_sort);
            $onlinehelp_lib->write_option('sort_order', $current_sort_order);
            $this->settings['sorted'] = $current_sort;
            $this->settings['sorted-order'] = $current_sort_order;
        }
    }

URLのパラメーターは $_GET から取得できますが、$_GET を直接使用するのではなく、filter_input 関数を使用します。その方が簡潔に記述できますし、値をフィルタリングできるためセキュリティ的観点からも有効です。
ソートする列は sort パラメーターから取得します(93行目)。item パラメーターの値は今回使用しません(94行目)。
現在ソートしている列とソートの順番は、WordPressのオプションテーブルに保存するようにしています。保存されているソート列と、クリックされた列を比較して、同じ列であればソート順序を変更し(102行目)、別の列であればその列でソートを行うようにします(104行目)。

get_option 関数の追加

WordPressにはオプションを読み取るための get_option 関数が用意されていますが、オンラインヘルプで使いやすいように、独自の get_option 関数を追加します。
まず、必要なデータを以下のように、Fow_OnlineHelp_Lib クラスに追加します。

    const OPTIONS = [
        'sort' => 'fow_oh_current_sort',
        'sort_order' => 'fow_oh_current_sort_order',
    ];

get_option 関数を、Fow_OnlineHelp_Lib クラスに追加します。

    /**
     * WordPressのオプションテーブルからオプション値を読み取る
     * @param   string  $option     オプション名
     * @param   mixed   $default    デフォルト値
     * @return  mixed   オプションの値
     */
    function get_option($option, $default)
    {
        return get_option(self::OPTIONS[$option], $default);
    }

write_option 関数の追加

オプションの値をWordPressに登録するための関数を追加します。Fow_OnlineHelp_Lib クラスに以下のコードを追加します。

    /**
     * WordPressのオプションテーブルに値を保存する
     * @param   string  $option オプション名
     * @param   mixed   $value  保存する値
     */
    function write_option($option, $value)
    {
        update_option(self::OPTIONS[$option], $value);
    }

validate_get 関数の呼び出し

作成したvalidate_get関数の呼び出しを、メイン処理に追加します。以下のように、onlinehelp_main.php にコードを追加します(26行目)。

$onlinehelp_admin = new Fow_OnlineHelp_Admin();
$onlinehelp_admin->validate_get();

このように記述すると validate_get 関数が実行されたあと、設定ページを出力する print_admin_page 関数が実行されます。validate_get 関数内でソートの設定を適切に記録し、print_admin_page 関数でソート設定を反映することで、ソートが実現されます。

fetch_helps 関数の修正

Fow_OnlineHelp_DB クラスの fetch_helps 関数でソートを処理できるように修正します。
以下のように修正します(30行目、62-74行目)。

/**
     * ヘルプの一覧を取得する
     * @param   int     $product    対象の製品ID
     * @param   int     $category   対象のカテゴリーID
     * @param   int     $sorted     ソートする列
     * @param   int     $order      ソートの順序(1:昇順 2:降順 else:なし)
     * @return  array   ヘルプの一覧
     */
    public function fetch_helps($product = 0, $category = 0, $sorted = 0, $order = 0)
    {
        global $wpdb;

        $table_help = $wpdb->prefix . Fow_OnlineHelp_Lib::FOW_OH_TABLES['helpbody'];
        $table_product = $wpdb->prefix . Fow_OnlineHelp_Lib::FOW_OH_TABLES['product'];
        $table_category = $wpdb->prefix . Fow_OnlineHelp_Lib::FOW_OH_TABLES['category'];

        $sql = "SELECT help_id, title, helpbody, tags, relations, th.product_id AS prod_id, prod_name AS product,
            category_id, cat_name AS category, th.created_at, th.updated_at
            FROM ($table_help AS th INNER JOIN $table_product ON th.product_id = $table_product.product_id)
            INNER JOIN $table_category ON th.category_id = $table_category.cat_id";

        $where = [];
        if (intval($product) !== 0) {
            $where[] = "(th.product_id = $product)";
        }
        if (intval($category) !== 0) {
            $where[] = "(category_id = $category)";
        }

        if (count($where) > 0) {
            $sql .= " WHERE ";

            for ($i = 0; $i < count($where) - 1; $i++) {
                if ($i > 0) {
                    $sql .= " AND ";
                }
                $sql .= $where[$i];
            }
        }

        $fields = [
            'title',
            'th.product_id',
            'category_id',
            'th.created_at',
            'th.updated_at',
        ];

        if ((intval($sorted) !== 0) && (intval($order) !== 0)) {
            $sql .= " ORDER BY " . $fields[$sorted] . (intval($order) === 1 ? ' ASC' : ' DESC');
        }

        $sql .= ';';

        return $wpdb->get_results($sql, OBJECT);
    }

これでソートできるようになったはずです。
設定ページを表示して、テーブルの列をクリックすると、数のようにソートの向きを示すマークが表示されることを確認しておいてください。

テーブルのソート – WordPressプラグインの作成 14」への1件のフィードバック

  1. kino_3240 投稿作成者

    validate_get関数に不具合がありましたので、以下のように修正しました。
    109行目
    (誤) $onlinehelp_lib->write_option('sort_order', $current_sort);

    (正) $onlinehelp_lib->write_option('sort_order', $current_sort_order);

    返信

コメントを残す

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

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