+44 (791) 5698 086

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';
 //print_r($columns);
 return $columns;
}
add_action( 'manage_ticket_posts_custom_column', 'nabtron_date_column_content', 100, 2 );
function nabtron_date_column_content( $column_name, $post_id ) {
 //print_r($column_name);
 if ( 'date-column' != $column_name )
 return;
 $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
 //unset($columns['date']);
 
 return $columns;
}
add_action( 'pre_get_posts', 'nabtron_date_orderby' );
function nabtron_date_orderby( $query ) {
 if( ! is_admin() )
 return;
 
 $orderby = $query->get( 'orderby');
 //print_r($orderby);
 
 if( 'date-url' == $orderby ) {
   // $query->set('meta_key','post_date');
   $query->set('orderby','post_date');
 }
}

Note, that if we setup the value of

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

to

 $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. Required fields are marked *

Who are we?

Nabtron team includes web, desktop software and mobile apps developers along with SEO professionals.

We are available 24 hours, 7 days a week. Contact us now for anything you need!

Join our mailing list

Lets become friend :) What's your name & email?