I have a custom post type called 'Courses'. I'm currently trying to automatically display them in the dashboard 'Courses' post list sorted by a date value specified in a custom field.
The date value is saved in d-m-Y format.
Using the code below I am able to sort the posts, but they are incorrectly ordered by the first number in the full date string (ie. the '01' in '01-12-19'), rather than the date.
function display_custom_posts_sorted_by_date($query) {
if (is_admin()) {
if (isset($query->query_vars['post_type'])) {
if ($query->query_vars['post_type'] == 'courses') {
$query->set('meta_key', 'online_start');
$query->set('orderby', 'meta_value');
$query->set('order', 'DESC');
}
}
}
}
add_filter('pre_get_posts' , 'display_custom_posts_sorted_by_date');
I already have functionality in place to manually sort the post list using a filterable column, discussed here - How to Sort by Date When Using d-m-Y Format
Is it possible to amend the 'meta_key' query in the function above so that it recognizes the d-m-Y date format?
Ymd
. Then you can just sort by the value numerically, and format the date for display in the template withdate()
.