WordPress : Sortable column on custom post type

Photo of author
Written By geekerhub

Lorem ipsum dolor sit amet consectetur pulvinar ligula augue quis venenatis. 

To make a wordpress sortable columns on a custom post type, one needs to follow the below steps:

  • Register column for the custom post type
  • Display column content
  • Register column as a sortable column
  • Register query based on sortable columns

One need to use this filter “manage_{$screen->id}_sortable_column” to make column sortable, where ‘$screen->id’ is ‘edit-{POST_TYPE_SLUG}

Let’s take an example that you would like to make ‘event_date‘ as a sortable column for your custom post type ‘event‘, then below code will be helpful

Register column for the custom post type

Suppose we like to add ‘event-date‘ as a sortable column to the ‘event‘ post type, below code snippet will be helpful:

/*
Register column for the custom post type
*/
function event_date_column_register( $columns ) {
$columns['event-date'] = __( 'Event Date', 'geekerhub' );
return $columns;
}
add_filter( 'manage_edit-event_columns', 'event_date_column_register' );

Below code snippet will display the content for above-registered column

Suppose we like to add ‘event-date’ as a sortable column to the ‘event’ post type, below code snippet will be helpful:

/*
Display column content
*/
function event_date_column_display( $column_name, $post_id ) {
	if ( 'event-date' != $column_name )
	return;

	$event_date = get_post_meta($post_id, 'event-date', true);

	if ( !$event_date )
	$event_date = '' . __( 'undefined', 'geekerhub' ) . '';

	echo $event_date;
}
add_action( 'manage_event_posts_custom_column', 'event_date_column_display', 10, 2 );

Register column as a wordpress sortable columns

Now we register our custom column as ‘sortable‘. As mentioned above we use the manage_{$screen->id}_sortable_column filter. The ‘$screen->id‘ in this case is ‘edit-event‘.
The key of the $columns array indicates a sortable column, and its value tells WordPress what to set ‘orderby‘ to in the query.

/*
Register column as a sortable column
*/
function event_date_column_register_sortable( $columns ) {
	$columns['event-date'] = 'event-date';
	return $columns;
}
add_filter( 'manage_edit-event_sortable_columns', 'event_date_column_register_sortable' );

Register query based on wordpress sortable columns

Now, we need to register a meta query based on sortable column value. Below code snippet will sort data based on the selected column. In our case, the column will be ‘event-date

/*
Register query based on sortable column
*/
function event_date_column_orderby( $vars ) {
	if ( isset( $vars['orderby'] ) && 'event-date' == $vars['orderby'] ) {
		$vars = array_merge( $vars, array(
		'meta_key' => 'event-date',
		'orderby' => 'meta_value',
		'order' => 'asc'
		) );
	}
	return $vars;
}
add_filter( 'request', 'event_date_column_orderby' );

Leave a Comment