wp_list_table()


WordPress関数wp_list_table()は、管理画面内でリストテーブルを作成し、データを表示するために使用されます。

構文

class WP_List_Table {
    public function prepare_items();
    public function display();
    public function search_box( $text, $input_id );
}

引数の説明:

  • $text (string) — 検索ボックスのラベル。
  • $input_id (string) — 入力フィールドのID。

例1: 基本的なリストテーブルの作成

以下はリストテーブルを作成する基本的な例です。

class My_List_Table extends WP_List_Table {
    public function prepare_items() {
        $this->items = array(
            array( 'ID' => 1, 'name' => 'Item 1' ),
            array( 'ID' => 2, 'name' => 'Item 2' ),
        );
    }
    public function display() {
        echo '<table>';
        foreach ( $this->items as $item ) {
            echo '<tr><td>' . $item['ID'] . '</td><td>' . $item['name'] . '</td></tr>';
        }
        echo '</table>';
    }
}
$table = new My_List_Table();
$table->prepare_items();
$table->display();

例2: 検索ボックスの追加

検索ボックスを追加する方法です。

class Searchable_List_Table extends WP_List_Table {
    public function search_box( $text, $input_id ) {
        echo '<form><input type="search" id="' . $input_id . '" placeholder="' . $text . '"></form>';
    }
}
$list_table = new Searchable_List_Table();
$list_table->search_box( '検索...', 'search-id' );

例3: ページネーションの実装

ページネーション付きのリストテーブルを作成する例です。

class Paginated_List_Table extends WP_List_Table {
    public function prepare_items() {
        $total_items = 100;
        $per_page = 10;
        $current_page = $this->get_pagenum();
        $this->items = array_slice( range(1, $total_items), ( $current_page - 1 ) * $per_page, $per_page );
    }
    public function display() {
        foreach ( $this->items as $item ) {
            echo '<p>Item: ' . $item . '</p>';
        }
    }
}
$table = new Paginated_List_Table();
$table->prepare_items();
$table->display();

例4: 列ヘッダーのカスタマイズ

カスタム列ヘッダーを表示する例です。

class Custom_Header_List_Table extends WP_List_Table {
    public function display() {
        echo '<table>';
        echo '<thead><tr><th>ID</th><th>Name</th></tr></thead>';
        foreach ( $this->items as $item ) {
            echo '<tr><td>' . $item['ID'] . '</td><td>' . $item['name'] . '</td></tr>';
        }
        echo '</table>';
    }
}

例5: 条件付きでデータを表示

条件を指定してデータをフィルタリングする方法です。

class Filtered_List_Table extends WP_List_Table {
    public function prepare_items() {
        $this->items = array(
            array( 'ID' => 1, 'status' => 'active' ),
            array( 'ID' => 2, 'status' => 'inactive' ),
        );
    }
    public function display() {
        foreach ( $this->items as $item ) {
            if ( $item['status'] === 'active' ) {
                echo '<p>Active Item: ' . $item['ID'] . '</p>';
            }
        }
    }
}
$table = new Filtered_List_Table();
$table->prepare_items();
$table->display();

関連機能: