Warning: Use of undefined constant user_level - assumed 'user_level' (this will throw an Error in a future version of PHP) in /home/users/1/juny/web/hidef/wp-content/plugins/ultimate-google-analytics/ultimate_ga.php on line 524

Warning: Use of undefined constant user_level - assumed 'user_level' (this will throw an Error in a future version of PHP) in /home/users/1/juny/web/hidef/wp-content/plugins/ultimate-google-analytics/ultimate_ga.php on line 524

[WordPress] 管理画面にテーブル(WP_List_Table)を表示する

公開日: : Web制作, wordpress


Warning: Use of undefined constant user_level - assumed 'user_level' (this will throw an Error in a future version of PHP) in /home/users/1/juny/web/hidef/wp-content/plugins/ultimate-google-analytics/ultimate_ga.php on line 524

WP_List_Table

管理画面で標準テーブルを表示したい場合は、WP_List_Tableを使用します。
標準テーブルとは何か?投稿一覧やユーザー一覧で表示されているテーブルです。
WP_List_Tableを使用することによって、ソートやページングなど少しの記述で動作するのですごく便利です。

サンプルのプラグイン

まずはサンプルのプラグインをインストールしてみます。
「Custom List Table Example」ってやつです。

スクリーンショット_2014-10-02_14_55_16
プラグイン > 新規作成 > 検索キーワードにCustom List Table Exampleと入力し、検索します。
表示されたら、いますぐインストール > 有効化
すると、設定に「List Table Example」という項目ができるので表示してみます。

 

スクリーンショット_2014-10-02_15_00_36
こんな感じです。テストデータが表示されています。

では、実際にソースコードを見てみましょう。
格納場所は「wp-content/plugins/custom-list-table-example/list-table-example.php」です。

コード

このサンプルファイルのソースを元に新規phpファイルを作成します。

修正箇所はおおまかに以下の通りです。

  • クラス名を変える
  • tt_add_menu_itemsを削除(設定に表示登録をしている処理です)
  • $example_dataを消し、実際に取得したいデータに変更する(連想配列)

次は、各関数の説明です。

__construct

function __construct(){
 global $status, $page;

 //Set parent defaults
 parent::__construct( array(
 'singular' => 'movie', //singular name of the listed records
 'plural' => 'movies', //plural name of the listed records
 'ajax' => false //does this table support ajax?
 ) );

}

コンストラクタです。movie、moviesの所を適宜に変更します。’ajax’は「ajaxサポートをするか否か」です。

column_default

function column_default($item, $column_name){
 switch($column_name){
 case 'rating':
 case 'director':
 return $item[$column_name];
 default:
 return print_r($item,true); //Show the whole array for troubleshooting purposes
 }
}

カラムのデフォルト設定です。rating、directorの箇所は列の識別子と思っていただければ分かりやすいかと。任意の好きな名前に変更してください。

column_識別子

function column_title($item){

 //Build row actions
 $actions = array(
 'edit' => sprintf('<a href="?page=%s&action=%s&movie=%s">Edit</a>',$_REQUEST['page'],'edit',$item['ID']),
 'delete' => sprintf('<a href="?page=%s&action=%s&movie=%s">Delete</a>',$_REQUEST['page'],'delete',$item['ID']),
 );

 //Return the title contents
 return sprintf('%1$s <span style="color:silver">(id:%2$s)</span>%3$s',
 /*$1%s*/ $item['title'],
 /*$2%s*/ $item['ID'],
 /*$3%s*/ $this->row_actions($actions)
 );
}

サンプルソースではcolumn_title、column_cbと定義されていますが、この関数は「column_列の識別子」です。
列に対して表示する処理を記述します。column_titleでは’title’という識別子でマウスオーバー時にedit、deleteというツールチップを表示しています。ツールチップはrow_actions関数で表示しています。

function column_cb($item){
 return sprintf(
 '<input type="checkbox" name="%1$s[]" value="%2$s" />',
 /*$1%s*/ $this->_args['singular'], //Let's simply repurpose the table's singular label ("movie")
 /*$2%s*/ $item['ID'] //The value of the checkbox should be the record's id
 );
}

チェックボックスの定義です。意味合いは、上記のcolumn_titleと同様です。
_args[‘singular’]でコンストラクタで定義した名前を取得しています。

get_columns

function get_columns(){
 $columns = array(
 'cb' => '<input type="checkbox" />', //Render a checkbox instead of text
 'title' => 'Title',
 'rating' => 'Rating',
 'director' => 'Director'
 );
 return $columns;
}

ここで列の識別子を決定します。キー=識別子、値=画面に表示する名称です。

get_sortable_columns

function get_sortable_columns() {
 $sortable_columns = array(
 'title' => array('title',false), //true means it's already sorted
 'rating' => array('rating',false),
 'director' => array('director',false)
 );
 return $sortable_columns;
}

ソート列の設定です。trueの場合はデフォルトでソートすることになります。

get_bulk_actions

function get_bulk_actions() {
    $actions = array(
        'delete'    => 'Delete'
    );
    return $actions;
}

一括操作の設定です。キー=アクションの名前、名前=画面で表示する名称です。

process_bulk_action

function process_bulk_action() {

 //Detect when a bulk action is being triggered...
 if( 'delete'===$this->current_action() ) {
 wp_die('Items deleted (or they would be if we had items to delete)!');
 }

}

一括操作の適用ボタン押下時の処理内容です。サンプルではwp_dieでメッセージを表示しているのみの状態になっています。
$this->current_action()は$_REQUEST[‘action’]あるいは$_REQUEST[‘action2’]とほぼ同じです。

prepare_items

function prepare_items() {
 global $wpdb; //This is used only if making any database queries

 $per_page = 5;

 $columns = $this->get_columns();
 $hidden = array();
 $sortable = $this->get_sortable_columns();

 $this->_column_headers = array($columns, $hidden, $sortable);

 $this->process_bulk_action();

 $data = $this->example_data;

 function usort_reorder($a,$b){
  $orderby = (!empty($_REQUEST['orderby'])) ? $_REQUEST['orderby'] : 'title'; //If no sort, default to title
  $order = (!empty($_REQUEST['order'])) ? $_REQUEST['order'] : 'asc'; //If no order, default to asc
  $result = strcmp($a[$orderby], $b[$orderby]); //Determine sort order
  return ($order==='asc') ? $result : -$result; //Send final sort direction to usort
 }
 usort($data, 'usort_reorder');

 $current_page = $this->get_pagenum();

 $total_items = count($data);

 $data = array_slice($data,(($current_page-1)*$per_page),$per_page);

 $this->items = $data;

 $this->set_pagination_args( array(
 'total_items' => $total_items, //WE have to calculate the total number of items
 'per_page' => $per_page, //WE have to determine how many items to show on a page
 'total_pages' => ceil($total_items/$per_page) //WE have to calculate the total number of pages
 ) );
 }

prepare_itemsでテーブル情報を設定します。

  • 2行目:$wpdbはDBアクセスクラスです。使用しない場合は削除します。
  • 4行目:1ページに表示する件数です。サンプルでは5行表示します。
  • 6〜8行目:列の設定です。$hiddenは表示しない列があれば設定します。
  • 10行目:列ヘッダーの設定です。
  • 12行目:一括操作の設定です。
  • 14行目:実際のデータの設定です。$example_dataを削除した場合はここでエラーになりますが、実際のデータを取得する処理を記述します。例えばデータベースのデータなどを表示したい場合は’ARRAY_A’の連想配列の形で取得します。
    $data = $wpdb->get_results("SELECT * FROM wp_posts", 'ARRAY_A');
  • 16〜22行目:ソートの設定です。データの型が数値型の場合は変換が必要です。
  • 24行目:現在のページ番号を設定します。
  • 26行目:取得データの全件数です。
  • 28行目:取得データを現在のページ分に分割します。
  • 30行目:取得データを設定します。
  • 32〜36行目:ページングの設定です。

後は、tt_render_list_pageの内容を表示したい場所に記述します。
表示部分は、

$testListTable->display();

その前に

$testListTable = new 定義したクラス名();
$testListTable->prepare_items();

をお忘れなく。

参考にWP_List_TableのCodexもご覧になってください。
関数リファレンス/WP_List_Table

ad

関連記事

[jQuery] クリック時に波紋のような効果をつける

今回は、クリックした時に波紋のような効果をつけるjQueryプラグインの紹介です。 Ripple

記事を読む

[html5] おさらいがてらWordPressのテーマを作るためにHTML5で一から作るよ![第4回]

完全に放置してました、僕です。 別に忘れていた訳じゃないんですが、時間がありませんでした。

記事を読む

[Dreamweaver] 不要な_notesを作成させない方法

みなさん、_notesで困ってませんか? Dreamweaverは、デフォルト設定で使用していると

記事を読む

[jQuery] Block Scrollプラグイン

今回は、ブロック毎にスクロールするjQueryプラグインのご紹介です。 Block Scroll

記事を読む

[CSS] 角丸は便利だけど理解に苦しむ時もある

一般的な角丸の使い方 よく使う角丸は、divを角丸にしたり、画像を角丸にしたりすることでしょう。

記事を読む

[WordPress] 管理画面にカラーピッカー(wp_color_picker)を表示する

カラーピッカー 管理画面でプラグインの設定などでカラーピッカーを表示したい場合、wp_color_

記事を読む

[CSS] 複数のbackground-imageの設定方法

マルチBackground-imageを使ってみる CSS3では、背景画像を指定する際に複数の画像

記事を読む

[html5] おさらいがてらWordPressのテーマを作るためにHTML5で一から作るよ![第1回]

現在、このブログはENJIさんが作られたSTINGER3という無料のテーマを利用させて頂いて

記事を読む

[CSS] animationを使ってみる!

色の変化をCSSのみで実装できる! CSS3のキーフレームアニメーションでは、JSで出来る、背景色

記事を読む

[Dreamweaver] オプション領域を極める!テンプレート上級編

オプション領域は、難しい! これまで、数回に渡りDreamweaverでのテンプレートの使い方を紹

記事を読む

ad

Message

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

ad

[PHP] curl転送してみる(googleに)

curlでgoogle画像検索APIにアクセスしてみます。 cu

[PHP] PDOでMySQLの接続確認をする

PDO PHPでMySQLに接続する際には、mysql_connec

[PHP] ランダムな英数字を生成する

便利系メソッド 今回はPHPでランダムな英数字を作成してみます。

[Swift] プロパティリスト(plist)の値を取得

plistからデータを取得してみます。 こちらのエントリーも参考にし

[Swift] Asset Catalogについて

XCode5から追加されたAsset Catalog。 いままで標準

→もっと見る

  • 1978年の七夕生まれ。 25才でweb業界の門を叩き、28才でフリーランスに。 現在は、フリーランスでマークアップ中心に、wordpressのカスタマイズやデザインをしております。 また、iPhoneアプリの開発もしております。

Warning: Use of undefined constant user_level - assumed 'user_level' (this will throw an Error in a future version of PHP) in /home/users/1/juny/web/hidef/wp-content/plugins/ultimate-google-analytics/ultimate_ga.php on line 524
PAGE TOP ↑

Warning: Use of undefined constant user_level - assumed 'user_level' (this will throw an Error in a future version of PHP) in /home/users/1/juny/web/hidef/wp-content/plugins/ultimate-google-analytics/ultimate_ga.php on line 524