Build a Custom Admin List Table in WordPress with WP_List_Table

Build an admin list table with WP_List_Table

The lists of posts, pages, users and comments in the admin are all built with the WP_List_Table class: columns, sorting links, bulk actions, row actions, pagination. A plugin that shows its own records (form leads, log entries, imports) can extend the same class and get a screen that looks and works exactly like the rest of the admin.

Problem: A plugin stores form leads in its own table and needs an admin screen to browse them with sorting, pagination and bulk delete.

Solution: Extend WP_List_Table: define the columns in get_columns(), the sortable ones in get_sortable_columns(), load the current page of rows in prepare_items(), and handle bulk actions before the table is displayed. The class is marked as private in core, so subclass it and test it after major WordPress updates.

The table class

<?php
if ( ! class_exists( 'WP_List_Table' ) ) {
    require_once ABSPATH . 'wp-admin/includes/class-wp-list-table.php';
}

class HA_Leads_Table extends WP_List_Table {

    public function __construct() {
        parent::__construct( array( 'singular' => 'lead', 'plural' => 'leads', 'ajax' => false ) );
    }

    public function get_columns() {
        return array(
            'cb'         => '<input type="checkbox">',
            'name'       => __( 'Name', 'textdomain' ),
            'email'      => __( 'Email', 'textdomain' ),
            'created_at' => __( 'Date', 'textdomain' ),
        );
    }

    protected function get_sortable_columns() {
        return array(
            'name'       => array( 'name', false ),
            'created_at' => array( 'created_at', true ), // true = already sorted (default column)
        );
    }

    protected function column_default( $item, $column_name ) {
        return esc_html( isset( $item[ $column_name ] ) ? $item[ $column_name ] : '' );
    }

    protected function column_cb( $item ) {
        return sprintf( '<input type="checkbox" name="lead[]" value="%d">', (int) $item['id'] );
    }

    protected function column_name( $item ) {
        $delete_url = wp_nonce_url(
            add_query_arg( array( 'action' => 'delete', 'lead' => (int) $item['id'] ) ),
            'ha_delete_lead_' . $item['id']
        );

        $actions = array(
            'delete' => sprintf( '<a href="%s">%s</a>', esc_url( $delete_url ), esc_html__( 'Delete', 'textdomain' ) ),
        );

        return '<strong>' . esc_html( $item['name'] ) . '</strong>' . $this->row_actions( $actions );
    }

    protected function get_bulk_actions() {
        return array( 'bulk-delete' => __( 'Delete', 'textdomain' ) );
    }

    public function prepare_items() {
        global $wpdb;

        $table    = $wpdb->prefix . 'ha_leads';
        $per_page = 20;
        $paged    = $this->get_pagenum();

        // Only known columns may be used in ORDER BY
        $allowed = array( 'name', 'created_at' );
        $orderby = isset( $_GET['orderby'] ) && in_array( $_GET['orderby'], $allowed, true ) ? $_GET['orderby'] : 'created_at';
        $order   = isset( $_GET['order'] ) && 'asc' === strtolower( $_GET['order'] ) ? 'ASC' : 'DESC';

        $total = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$table}" );

        $this->items = $wpdb->get_results( $wpdb->prepare(
            "SELECT id, name, email, created_at FROM {$table} ORDER BY {$orderby} {$order} LIMIT %d OFFSET %d",
            $per_page,
            ( $paged - 1 ) * $per_page
        ), ARRAY_A );

        $this->set_pagination_args( array( 'total_items' => $total, 'per_page' => $per_page ) );
        $this->_column_headers = array( $this->get_columns(), array(), $this->get_sortable_columns() );
    }
}

Column and table names cannot be passed through prepare(), so the sort column is checked against a list of allowed names instead.

The page and the actions

<?php
add_action( 'admin_menu', function () {
    add_menu_page( 'Leads', 'Leads', 'manage_options', 'ha-leads', 'ha_render_leads_page', 'dashicons-email', 26 );
} );

function ha_render_leads_page() {
    global $wpdb;

    $table = new HA_Leads_Table();

    // One row: ?action=delete&lead=5 with its own nonce
    if ( 'delete' === $table->current_action() && isset( $_GET['lead'] ) ) {
        $id = absint( $_GET['lead'] );
        check_admin_referer( 'ha_delete_lead_' . $id );
        $wpdb->delete( $wpdb->prefix . 'ha_leads', array( 'id' => $id ), array( '%d' ) );
    }

    // Bulk: the form nonce is printed by the table as bulk-{plural}
    if ( 'bulk-delete' === $table->current_action() && ! empty( $_POST['lead'] ) ) {
        check_admin_referer( 'bulk-leads' );
        foreach ( array_map( 'absint', (array) $_POST['lead'] ) as $id ) {
            $wpdb->delete( $wpdb->prefix . 'ha_leads', array( 'id' => $id ), array( '%d' ) );
        }
    }

    $table->prepare_items();

    echo '<div class="wrap"><h1>' . esc_html__( 'Leads', 'textdomain' ) . '</h1>';
    echo '<form method="post">';
    $table->display();
    echo '</form></div>';
}

The capability in add_menu_page() protects the page itself; the nonces protect the delete actions against requests sent from other sites.

NOTE: After a delete, redirect back to the list (with wp_safe_redirect() on admin_init, before any output) instead of showing the table in the same request; otherwise reloading the page repeats the action. The example handles it inline to stay short.