WP List Table Tutorial – Add Data Sorting To List

We create wordpress admin tables using WP_List_Table class to show data. This class also provides method for data sorting. In this tutorial we will see how to add data sorting to WordPress admin table.

Data sorting means data sort in manner of ascending or descending order. There is a bit logical implementation you need to focus on.

Probably while working with wordpress admin tables of Post, Pages, Users, etc you have seen this triangle icon over column names. You will see either up or down. Up shows data sort in ascending order. Down shows data sort in descending order.

We will see here how to add this data sorting icon to wordpress admin table.

Add Sorting to List Table

WP_List_Table class provides a method to add data sorting feature to list tables. Assuming we are adding data sorting to users data.

In this last tutorial we have seen how to show users data into list table.

protected function get_sortable_columns()
{
      $sortable_columns = array(
            'user_login'  => array('user_login', false),
            'display_name' => array('display_name', false),
            'user_email'   => array('user_email', true)
      );
      return $sortable_columns;
}

get_sortable_columns() a method of WP_List_Table class.

'user_login'  => array('user_login', false),

OR

'user_login'  => array('user_login', true),

user_login is the column key identifier. In the value section we have an array. In the second value of array we can have true or false value. If any column is missing here inside this method, means no sorting function will be available for that.

If the value is true, then arrow will come up in position. When we click on it data will sorted in ascending order with respective of that column.

If the value is false, then arrow will come down in position. When we click on it data will sorted in descending order with respective of that column.

Above code will add only the sorting icons to columns (user_login, user_email, display_name) either in UP or DOWN position. We need to do code for it own.

Next,

Let’s add the code for ascending or descending order.

Add Data Sorting Function

// Sorting function
function usort_reorder($a, $b)
{
      // If no sort, default to user_login
      $orderby = (!empty($_GET['orderby'])) ? $_GET['orderby'] : 'user_login';

      // If no order, default to asc
      $order = (!empty($_GET['order'])) ? $_GET['order'] : 'asc';

      // Determine sort order
      $result = strcmp($a[$orderby], $b[$orderby]);

      // Send final sort direction to usort
      return ($order === 'asc') ? $result : -$result;
}

We need to add this function to our created class.

function prepare_items()
{
      //...

      $sortable = $this->get_sortable_columns();

      usort($this->users_data, array(&$this, 'usort_reorder'));
      
      //...
}

$this->users_data contains users data. usort_reorder is the sorting function name.

Plugin Setup

Here, is the complete code of plugin.

<?php
/*
Plugin Name:  Simple Employees Table
Description: It displays a table with employee data
Author: Online Web Tutor
Author URI: https://onlinewebtutorblog.com/
License: GPLv2 or later
License URI: https://www.gnu.org/licenses/gpl-2.0.html
Text Domain: basic-wp-list-table
Version: 1.0
*/

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

// Extending class
class Employees_List_Table extends WP_List_Table
{
      private $users_data;

      private function get_users_data()
      {
            global $wpdb;

            return $wpdb->get_results(
                  "SELECT ID,user_login,user_email,display_name from {$wpdb->prefix}users",
                  ARRAY_A
            );
      }

      // Define table columns
      function get_columns()
      {
            $columns = array(
                  'cb'            => '<input type="checkbox" />',
                  'ID' => 'ID',
                  'user_login' => 'Username',
                  'display_name'    => 'Name',
                  'user_email'      => 'Email'
            );
            return $columns;
      }

      // Bind table with columns, data and all
      function prepare_items()
      {
            $this->users_data = $this->get_users_data();
            
            $columns = $this->get_columns();
            $hidden = array();
            $sortable = $this->get_sortable_columns();
            $this->_column_headers = array($columns, $hidden, $sortable);

            usort($this->users_data, array(&$this, 'usort_reorder'));

            $this->items = $this->users_data;
      }

      // bind data with column
      function column_default($item, $column_name)
      {
            switch ($column_name) {
                  case 'ID':
                  case 'user_login':
                  case 'user_email':
                        return $item[$column_name];
                  case 'display_name':
                        return ucwords($item[$column_name]);
                  default:
                        return print_r($item, true); //Show the whole array for troubleshooting purposes
            }
      }

      // To show checkbox with each row
      function column_cb($item)
      {
            return sprintf(
                  '<input type="checkbox" name="user[]" value="%s" />',
                  $item['ID']
            );
      }

      // Add sorting to columns
      protected function get_sortable_columns()
      {
            $sortable_columns = array(
                  'user_login'  => array('user_login', false),
                  'display_name' => array('display_name', false),
                  'user_email'   => array('user_email', true)
            );
            return $sortable_columns;
      }

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

// Adding menu
function my_add_menu_items()
{
      add_menu_page('Employees List Table', 'Employees List Table', 'activate_plugins', 'employees_list_table', 'employees_list_init');
}
add_action('admin_menu', 'my_add_menu_items');

// Plugin menu callback function
function employees_list_init()
{
      // Creating an instance
      $empTable = new Employees_List_Table();

      echo '<div class="wrap"><h2>Employees List Table</h2>';
      // Prepare table
      $empTable->prepare_items();
      // Display table
      $empTable->display();
      echo '</div>';
}

Plugin

Go to Plugins >> Installed Plugins

Click on Activate

It will create a admin menu. When we click on it.

When you click on column names. If column has up arrow then you will get query string as –

?page=employees_list_table&orderby=user_email&order=asc

And if column has down arrow, then query string will be –

?page=employees_list_table&orderby=user_email&order=desc

Query string contains the page name in which you are, orderby means which column used and order means sorting is in ascending or descending order.

Now, successfully we have implemented the sorting feature to wordpress admin table.

Sanjay KumarHello friends, I am Sanjay Kumar a Web Developer by profession. Additionally I'm also a Blogger, Youtuber by Passion. I founded Online Web Tutor and Skillshike platforms. By using these platforms I am sharing the valuable knowledge of Programming, Tips and Tricks, Programming Standards and more what I have with you all. Read more