WordPress

Change Sortable Columns In WordPress

In a previous tutorial we saw how you can recreate the All Posts table in the WordPress admin area by using the WP_List class in WordPress.

It talks about creating your own table and populating it with any data that you need. It talks about how you can customise the table to behaviour in anyway that is needed by adding different columns to the table, assigning sortable columns to the table, pagination and searching the data, just like you can in the All posts table.

But in this previous tutorial only explains how to create sortable columns on a new table, in this tutorial we are going to look at changing an existing table to apply new sortable columns.

To edit the columns and change them to be sortable we need to use a filter and return is a set of column IDs of what columns we want to be sortable. The filter we need to use is manage_edit-{$this->screen->id}_sortable_columns.

add_filter( 'manage_edit-{$this->screen->id}_sortable_columns', 'manage_sortable_columns');

The below code snippet will change the author column on the posts screen to be sortable.

class Pu_Manage_Sortable_Columns
{
    public function __construct()
    {
        add_filter( 'manage_edit-post_sortable_columns', array($this, 'manage_sortable_columns'));
    }

    public function manage_sortable_columns( $columns )
    {
        $columns['author'] = 'Author';

        return $columns;
    }
}

Now you will see that the author column is sortable which is noticeable by the sort arrow appearing next to the Author title on the hover event. Clicking on the author title will now sort the table data by the Author name.

Back to top

Learn how to code with Treehouse

  • Learn projects with access to 1000+ videos
  • Practice live with our Code Challenge Engine
  • Get help in our members-only forums

Start with a 7 day free trial