Automatically sorting custom post type admin area by a custom field

Rather save the event meta field date(s) as a unix-timestamp, instead of a string, or you’ll be making life too difficult for yourself. It just makes date comparisons so much easier.

Here’s an example of how to convert your YYYY/MM/DD format to a unix timestamp:

$date="2010/09/22";
$dateParts = explode("https://wordpress.stackexchange.com/", trim($date));
if (count($dateParts) == 3) {
    $timestamp = mktime(0, 0, 0, $dateParts[1], $dateParts[2], $dateParts[0]);
} else {
    $timestamp = 0; 
    // The input value is dodgy, therefore the timestamp is set to 0, which is 
    // effectively 1970-01-01T00:00:00Z.
}

To convert back again for user editing and displaying, it’s as simple as:

$displayValue = date('Y/m/d', $timestamp);

I’d also recommend that you name your custom field something more specific, like gs_event_date?

After you have done that, create your filter:

function gs_events_pre_get_posts($query) {

    // Note: Use the $pagenow global for finer grained checking, 
    // if you want to. There are many examples out there.

    // Your question pertains to admin use only...

    if (is_admin()) {

        // Present the posts in your meta_key field's order in admin

        if (isset($query->query_vars['post_type'])) {
            if ($query->query_vars['post_type'] == 'gs_events') {

                $query->set('meta_key', 'gs_event_date');
                $query->set('orderby', 'meta_value');
                $query->set('order', 'ASC');

                // ...and if you only want your future events to be 
                // displayed in admin, you can uncomment the following:

                // $query->set('meta_compare', '>=');
                // $query->set('meta_value', time());

                // Note: The use of time() is quick-and-dirty here, 
                // in reality you'll need to adjust the timezone, 
                // check server-time vs local time, etc.
            }
        }
    }
}

Add your filter…

add_filter('pre_get_posts' , 'gs_events_pre_get_posts');

Leave a Comment