Adding custom columns with sorting option in WordPress for post types

WordPress comes with great features that are very user friendly and easy to understand. But, when you want to do some customization, it is hard to depend on a plugin for everything. Instead you can get your hands dirty by trying some code.

What if you want to decide what all the columns that needs to be shown in the archive page of a post type in wp-admin.

Part 1 : Show the column names in the table

Following code is an example of

  • How to remove unwanted existing columns like Published date, author etc..
  • How to add custom columns that might be post meta or other post data.

NOTE : The hook changes according to post slug. If my post type was ‘product’, the hook would have been ‘manage_edit-product_column’

Part 2 : Show relevant data in the columns we added

Using switch case, we pull data for each custom column we added. Sometimes we can override the predefined columns in WordPress using this hook.

Override predefined columns

You can add a switch case to override post title by adding “case title” and you can define what text to be showed in the title column of your post archive.

How to find the slug of pre defined columns

Using inspect tool, check the table header of the archive table. There hover to the column which you wanna override. There in inspect tool, you will see the slug of each table header in the attribute called “id“. Please check following screenshot.

Part 3 : Add sorting facility to the custom columns

First we need to make our custom column “Sortable”. For this we need to use following hook. Where we can define which columns should be sortable and which need not.

Now our custom column is sortable. Next part is to write logic for sorting. The best way to do this is to hook into pre_get_posts action hook. This will check the orderby query in WP_Query and applied sorting accordingly.

Share this post