Sortable Event Date Column for Events
Adds "Starts" and "Venue" columns to the Events admin list, sorts the list by start date by default and lets you click to reverse it.
Opens WPIDE on
Code
add_filter( 'manage_event_posts_columns', function ( $columns ) {
$date = $columns['date'] ?? null;
unset( $columns['date'] );
$columns['event_start'] = 'Starts';
$columns['event_venue'] = 'Venue';
if ( $date ) {
$columns['date'] = $date;
}
return $columns;
} );
add_action( 'manage_event_posts_custom_column', function ( $column, $post_id ) {
if ( 'event_start' === $column ) {
$date = date_create_immutable( (string) get_post_meta( $post_id, '_event_start', true ), wp_timezone() );
echo $date && get_post_meta( $post_id, '_event_start', true ) ? esc_html( wp_date( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), $date->getTimestamp() ) ) : '—';
} elseif ( 'event_venue' === $column ) {
echo esc_html( get_post_meta( $post_id, '_event_venue', true ) ?: '—' );
}
}, 10, 2 );
add_filter( 'manage_edit-event_sortable_columns', function ( $columns ) {
$columns['event_start'] = 'event_start';
return $columns;
} );
// Sort with a LEFT JOIN so events without a date stay in the list.
add_filter( 'posts_clauses', function ( $clauses, $query ) {
global $wpdb;
if ( ! is_admin() || ! $query->is_main_query() || 'event' !== $query->get( 'post_type' ) || ! in_array( $query->get( 'orderby' ), array( '', 'event_start' ), true ) ) {
return $clauses;
}
$order = 'ASC' === strtoupper( (string) $query->get( 'order' ) ) ? 'ASC' : 'DESC';
$clauses['join'] .= $wpdb->prepare( " LEFT JOIN {$wpdb->postmeta} AS wpide_ev ON ( wpide_ev.post_id = {$wpdb->posts}.ID AND wpide_ev.meta_key = %s )", '_event_start' );
$clauses['orderby'] = "wpide_ev.meta_value {$order}, {$wpdb->posts}.post_date DESC";
return $clauses;
}, 10, 2 );
Notes
Reads the fields saved by the Event Details meta box snippet.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.