Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Change Sortable Columns In WordPress

DZone's Guide to

Change Sortable Columns In WordPress

· Web Dev Zone
Free Resource

Learn how to build modern digital experience apps with Crafter CMS. Download this eBook now. Brought to you in partnership with Crafter Software

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.

Crafter is a modern CMS platform for building modern websites and content-rich digital experiences. Download this eBook now. Brought to you in partnership with Crafter Software.

Topics:

Published at DZone with permission of Paul Underwood, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}