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?

  • You will have a much easier time if you just store the date as Ymd. Then you can just sort by the value numerically, and format the date for display in the template with date(). Commented Jul 12, 2019 at 8:52
  • Thanks Jacob. Unfortunately we already have multiple pieces of existing functionality throughout the website that utilize the d-m-Y format. The website is also quite large and changing the date format is not really feasible here.
    – Connor
    Commented Jul 13, 2019 at 0:58


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.