Sort custom column date in custom post type

This post is to simply include the code required to create a sortable date column in a custom post type.

I was working with awesome support plugin and had to do several modifications to it. One of that required us to have a custom column for publish date of the post including the time of publishing and then making that column sortable.

wordpress 4.0

We are using admin columns pro on the site too but for some reasons the code wouldn’t allow auto sorting. So had to do that manually.

Before sharing the code, I would like to mention that I tried numerous things, from published_date in meta_key field and others like original_date and so on, but things didn’t work out (probably due to my ignorance and lack of knowledge!). Ultimately setting up orderby┬áto “post_date” and totally commenting out meta_key and meta value worked! phew!

This is the working code and I’ve named the variables and values in it to make them clear and how to use.

The code is as follows.

add_filter('manage_edit-ticket_columns', 'nabtron_extra_date_columns');
function nabtron_extra_date_columns($columns) {
 $columns['date-column'] = 'date-heading';
 return $columns;
add_action( 'manage_ticket_posts_custom_column', 'nabtron_date_column_content', 100, 2 );
function nabtron_date_column_content( $column_name, $post_id ) {
 if ( 'date-column' != $column_name )
 $format = 'Y/m/d - g:i a';
 $date = get_the_date( $format, $post_id );
 echo $date;
add_filter( 'manage_edit-ticket_sortable_columns', 'nabtron_sortable_date_column' );
function nabtron_sortable_date_column( $columns ) {
 // $columns['columns-original-name'] = 'what-url-query-should-contain';
 $columns['date-column'] = 'date-url';
 $columns['column-date_published'] = 'date_published';
 //To make a column 'un-sortable' remove it from the array
 return $columns;
add_action( 'pre_get_posts', 'nabtron_date_orderby' );
function nabtron_date_orderby( $query ) {
 if( ! is_admin() )
 $orderby = $query->get( 'orderby');
 if( 'date-url' == $orderby ) {
   // $query->set('meta_key','post_date');

Note, that if we setup the value of

 $columns['date-column'] = 'date-url';


 $columns['date-column'] = 'post_date'; // or published_date

We might not be needing the last function and hook and it will sort out the stuff itself.
If you need any details or help for this code or any feature you’re working on for your wordpress site or plugin, do let me know!

Leave a Reply

Your email address will not be published.