WordPress: Customizing sort order for custom post types

July 12, 2012

By default in WordPress a custom post type is sorted by it’s published date when viewing the page listing the posts. Depending upon your requirements this may not be desirable. WordPress includes a hook called parse_query that allows us to hook into the query arguments that are sent when retrieving data for the page. It is pretty simple to change this. It is important to understand though that the parse_query hook gets fired in many location inside wp-admin. You should always check to make sure you are on the correct page before altering the query or you may end up altering the entire system in a way you did not intend. Here is the code you will need.

add_filter( 'parse_query', 'my_custom_post_sort' );
function my_custom_post_sort($query) {
    if( is_admin() && isset( $_GET['post_type'] ) && $_GET['post_type'] == 'tribe_events' ) {
        $query->query_vars['orderby'] = 'meta_value';
        $query->query_vars['meta_key'] = '_EventStartDate';
        $query->query_vars['order'] = 'ASC';
    }
}