my alt

Creating a Custom WordPress Admin Table with WP_List_Table

In this article, we will explore how to create a custom WordPress admin table using the WP_List_Table class. This class provides a powerful interface for displaying tabular data in the WordPress admin area, complete with sortable columns, pagination, and more.

For our example, we will assume that we have a JSON file containing a list of fictional books, each with a title, author, genre, and publication year. Our goal is to display this data in a sortable table in the WordPress admin area.

Preparing the Data

First, let’s assume that we have a JSON file named books.json in the wp-content/uploads directory. The file contains an array of objects, each representing a book:

[
    {"title": "The Great Novel", "author": "John Doe", "genre": "Fiction", "year": 2005},
    {"title": "History of the World", "author": "Jane Doe", "genre": "History", "year": 2010},
    // More books...
]

Note that this is just an example for the sake of exampling the code. You could use any data – from JSON files to Database entries.

Creating the List Table Class

Next, we will create a new class that extends the WP_List_Table class. This class will handle reading the JSON file, preparing the data, and displaying the table.

// Include the necessary WordPress files
if (!class_exists('WP_List_Table')) {
    require_once(ABSPATH . 'wp-admin/includes/class-wp-list-table.php');
}

class Books_List_Table extends WP_List_Table {
    public function __construct() {
        parent::__construct(array(
            'singular' => 'Data',
            'plural'   => 'Data',
            'ajax'     => false
        ));
    }
}

Defining the Columns

The get_columns method defines the columns for the table. Each key in the returned array is the column ID, and the corresponding value is the column title.

public function get_columns() {
    return array(
        'title'  => 'Title',
        'author' => 'Author',
        'genre'  => 'Genre',
        'year'   => 'Year'
    );
}

Sorting the Columns

The get_sortable_columns method defines which columns are sortable. Each key in the returned array is the column ID, and the corresponding value is an array with the column ID and the initial sorting order.

public function get_sortable_columns() {
    return array(
        'title'  => array('title', false),
        'author' => array('author', false),
        'year'   => array('year', false)
    );
}

Preparing the Items

The prepare_items method reads the JSON file, decodes the data, sorts it, and assigns it to the items property. It also sets the column headers using the _column_headers property.

public function prepare_items() {
    // Include the WordPress filesystem API
    require_once(ABSPATH . 'wp-admin/includes/file.php');
    WP_Filesystem();
    global $wp_filesystem;

    // Get the path to the JSON file
    $upload_dir = wp_upload_dir();
    $file_path = $upload_dir['basedir'] . '/books.json';

    // Get the contents of the JSON file
    $json = $wp_filesystem->get_contents($file_path);

    // Decode the JSON data into an array
    $data = json_decode($json, true);

    // Sort the data
    usort($data, array($this, 'usort_reorder'));

    $this->_column_headers = array($this->get_columns(), array(), $this->get_sortable_columns());
    $this->items = $data;
}

Displaying the Data

The column_default method defines how each column is displayed. It takes an item and a column name as parameters, and returns the corresponding data.

public function column_default($item, $column_name) {
    return $item[$column_name];
}

Sorting the Data

The usort_reorder method is used to sort the data based on the orderby and order parameters in the URL. This allows you to click on the column headers to sort the table.


private function usort_reorder($a, $b) {
    $orderby = (!empty($_GET['orderby'])) ? $_GET['orderby'] : 'title'; // If no sort, default to title
    $order = (!empty($_GET['order'])) ? $_GET['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
}

Display the table

Now, we can display this table anywhere we want – maybe in a WordPress Custom Admin Page?


// Create an instance of our package class
$Books_List_Table = new Books_List_Table();
// Fetch, prepare, sort, and filter our data
$Books_List_Table->prepare_items();
?>

<div class="wrap">
    <h2>My Custom List Table</h2>
    <form method="get">
        <input type="hidden" name="page" value="<?php echo $_REQUEST['page'] ?>" />
        <?php $Books_List_Table->display() ?>
    </form>
</div>

Conclusion

By extending the WP_List_Table class, we can create powerful, sortable tables in the WordPress admin area. This provides a flexible and consistent interface for displaying tabular data, and can be adapted to a wide range of use cases. The best? It almost needs no code!

This code is not optimised for WordPress Coding Standards, neither does it follow best security practices. To use it in production, you would want to rewrite this code and make sure to apply all necessary standards