Get 50% Discount Offer 26 Days

Recommended Services
Supported Scripts
WordPress
Hubspot
Joomla
Drupal
Wix
Shopify
Magento
Typeo3
How to Create a Custom Table Listing in WordPress Admin Using WP_List_Table

If you’ve ever worked with WordPress, you’re likely familiar with how the admin interface organizes content such as posts, pages, and users in a table format. But what if you want to create a similar table for custom data or records in your plugin or theme? WordPress makes this easy using the WP_List_Table class, which allows developers to build tables that support searching, sorting, pagination, and bulk actions.

This guide will explain how to use WP_List_Table to create a custom table listing in the WordPress admin area. We will walk through every step, from extending the class to displaying the table with advanced functionality, including search, sort, pagination, and bulk actions. You will also find code examples, explanations, and helpful tips along the way.

What Is WP_List_Table?

Before diving into the code, let’s briefly explain what WP_List_Table is and why it’s important for building custom tables in WordPress.

WP_List_Table is a class included in WordPress that helps developers manage tabular data in the admin area. This class is not directly accessible from the theme or plugin, but you can extend it to create custom tables. Many WordPress built-in admin screens, like the posts, pages, and users listings, use WP_List_Table under the hood.

It provides useful methods and hooks for tasks like sorting, pagination, searching, and displaying actions on each row. By extending this class, you can create a table that behaves exactly like the default WordPress tables.

Custom Table Listing in WordPress Admin Using WP_List_Table

Step-by-Step Guide to Creating a Custom Table

Now, let’s start by creating a custom table listing using WP_List_Table. Follow the steps below to build a table that allows sorting, searching, pagination, and bulk actions. We’ll go through the steps one by one, providing detailed explanations.

Step 1: Extend the WP_List_Table Class

First, we need to create a custom class that extends WP_List_Table. This class will hold all the logic to manage our custom table.

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

    class Custom_Table_List extends WP_List_Table {

        // Define the columns for the table
        public function get_columns() {
            $columns = [
                'cb' => '<input type="checkbox" />', // Checkbox column for bulk actions
                'title' => __('Title', 'textdomain'),
                'date' => __('Date', 'textdomain'),
            ];
            return $columns;
        }

        // Fetch data to display in the table
        public function prepare_items() {
            global $wpdb;
            $per_page = $this->get_items_per_page('posts_per_page');
            $paged = isset($_GET['paged']) ? $_GET['paged'] : 1;
            $offset = ($paged - 1) * $per_page;

            // Query your custom data here (you could change this based on your needs)
            $query = "SELECT * FROM {$wpdb->prefix}your_custom_table LIMIT %d, %d";
            $data = $wpdb->get_results($wpdb->prepare($query, $offset, $per_page));

            // Pagination and sorting
            $total_items = $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->prefix}your_custom_table");

            $this->items = $data;
            $this->set_pagination_args([
                'total_items' => $total_items,
                'per_page' => $per_page,
            ]);
        }

        // Display content of each column
        public function column_default($item, $column_name) {
            switch ($column_name) {
                case 'title':
                    return $item->title; // Display title
                case 'date':
                    return $item->date; // Display date
                default:
                    return print_r($item, true); // Debugging
            }
        }
    }
}

Step 2: Defining Sortable Columns

Sorting is one of the most crucial features of a table, especially when you have a lot of data. WordPress allows you to define which columns can be sorted. We do this by overriding the get_sortable_columns() method.

// Define sortable columns
public function get_sortable_columns() {
    $sortable_columns = [
        'title' => ['title', true],  // true means ascending order by default
        'date' => ['date', false],   // false means descending order by default
    ];
    return $sortable_columns;
}

By defining this, WordPress will automatically add sorting links to the columns that are marked as sortable. This process makes it easy for users to reorder the data by clicking the column headers.

Step 3: Searching the Data

Adding a search functionality allows users to filter the data in the table by keywords. You can easily implement search by overriding the search_items() method in your custom table class.

Here’s an example of how to implement a search feature:

// Searching
public function search_items($search_term) {
    global $wpdb;
    $query = "SELECT * FROM {$wpdb->prefix}your_custom_table WHERE title LIKE %s";
    return $wpdb->get_results($wpdb->prepare($query, '%' . $wpdb->esc_like($search_term) . '%'));
}

This code ensures that when the user types a query into the search box, the table sort the results based on the search term in the “title” column.

Step 4: Pagination

For tables with a lot of data, pagination is essential. Without pagination, loading all records at once can slow down the page and make the table unusable. WordPress handles pagination through set_pagination_args().

public function prepare_items() {
    global $wpdb;
    $per_page = $this->get_items_per_page('posts_per_page');
    $paged = isset($_GET['paged']) ? $_GET['paged'] : 1;
    $offset = ($paged - 1) * $per_page;

    // Query your custom data here (you could change this based on your needs)
    $query = "SELECT * FROM {$wpdb->prefix}your_custom_table LIMIT %d, %d";
    $data = $wpdb->get_results($wpdb->prepare($query, $offset, $per_page));

    // Pagination and sorting
    $total_items = $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->prefix}your_custom_table");

    $this->items = $data;
    $this->set_pagination_args([
        'total_items' => $total_items,
        'per_page' => $per_page,
    ]);
}

This function ensures that your table will display only a limited number of rows per page, and users can navigate through pages to view all data.

Step 5: Implementing Bulk Actions

WordPress provides a built-in system for bulk actions, which is useful for actions like deleting multiple records at once. You can define your bulk actions by overriding the get_bulk_actions() method.

// Define bulk actions
public function get_bulk_actions() {
    $actions = [
        'delete' => __('Delete', 'textdomain'),
    ];
    return $actions;
}

// Handle bulk action
public function process_bulk_action() {
    if ('delete' === $this->current_action()) {
        // Handle deletion of selected items
        $ids = isset($_GET['id']) ? $_GET['id'] : [];
        foreach ($ids as $id) {
            // Perform the deletion (this could be done with a custom database query)
            global $wpdb;
            $wpdb->delete("{$wpdb->prefix}your_custom_table", ['ID' => $id]);
        }
    }
}

This function enables users to select multiple rows and delete them with a single click, which is crucial for managing large datasets.

Step 6: Displaying the Custom Table

After implementing all the necessary methods, you need to display the table on a custom admin page. Use the add_menu_page() function to create a new admin menu item, and use the Custom_Table_List class to display the table.

function add_custom_table_page() {
    $page_title = 'Custom Table';
    $menu_title = 'Custom Table';
    $capability = 'manage_options';
    $menu_slug = 'custom_table_page';
    $function = 'custom_table_page_callback';
    $icon_url = 'dashicons-list-view';
    $position = 6;

    add_menu_page($page_title, $menu_title, $capability, $menu_slug, $function, $icon_url, $position);
}

function custom_table_page_callback() {
    $table = new Custom_Table_List();
    $table->prepare_items();
    ?>
    <div class="wrap">
        <h1 class="wp-heading-inline">Custom Table</h1>
        <form method="post">
            <input type="hidden" name="page" value="custom_table_page" />
            <?php
            $table->display();
            ?>
        </form>
    </div>
    <?php
}

add_action('admin_menu', 'add_custom_table_page');

This code creates a new menu item in the WordPress admin sidebar called “Custom Table.” When clicked, it will display your custom table with the functionalities we’ve added (sorting, searching, pagination, and bulk actions).

Frequestly Asked Questions:

You add custom data by modifying the prepare_items() method where the SQL query fetches your custom data from the database.

In the process_bulk_action() method, check for the bulk action (delete), then perform a query to delete the selected rows.

Yes! You can create custom filters in the form of dropdowns or search fields and handle the filtering logic in prepare_items().

You can implement Ajax for features like live search, sorting, and bulk actions. WordPress provides functions like admin-ajax.php to enable Ajax requests in the admin panel.

Yes, this method will work with any theme as long as you add the necessary hooks and ensure your custom table class is correctly instantiated in the admin pages.

Conclusion

By using WP_List_Table, we can create robust, scalable, and interactive custom tables in the WordPress admin. This process allows you to present data in a way that is manageable and user-friendly, with powerful features like sorting, searching, pagination, and bulk actions. The implementation is straightforward but provides a great deal of flexibility. Whether you’re a beginner or an advanced user, you can customize these tables to fit your needs!

About the writer

Hassan Tahir Author

Hassan Tahir wrote this article, drawing on his experience to clarify WordPress concepts and enhance developer understanding. Through his work, he aims to help both beginners and professionals refine their skills and tackle WordPress projects with greater confidence.

Leave a Reply

Your email address will not be published. Required fields are marked *

Lifetime Solutions:

VPS SSD

Lifetime Hosting

Lifetime Dedicated Servers