I would like to sortable a column with custom data. I have a custom post type named "events" and I have a custom meta_key named "_start_at".
My column is sortable but when I click on, my posts are ordrered by date of publication and not by date "start_at".
How can i do this ?
This is my code :
function my_set_sortable_columns( $columns )
{
$columns['dateevent'] = 'dateevent';
return $columns;
}
add_filter( 'manage_edit-event_sortable_columns', 'my_set_sortable_columns' );
function my_sort_custom_column_query( $query )
{
$orderby = $query->get( 'orderby' );
if ( 'dateevent' == $orderby ) {
$meta_query = array(
'relation' => 'OR',
array(
'key' => '_start_at',
'compare' => 'NOT EXISTS',
),
array(
'key' => '_start_at',
),
);
$query->set( 'meta_query', $meta_query );
$query->set( 'orderby', '_start_at' );
}
}
add_action( 'pre_get_posts', 'my_sort_custom_column_query' );
_start_at
as the array key for one of the arrays in yourmeta_query
array. That's how we sort by a specific meta query clause.start_at
meta value? Can you give some sample values?Y-m-d H:i:s
. Because otherwise, sorting the values won't be easy. Did you use a plugin to add the meta; if so, what plugin?