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';
    }
}

 

2 thoughts on “WordPress: Customizing sort order for custom post types

  1. Jeff (July 12, 2012)

    Digging this little bit of code. Is this specific to ordring custom post types in the back end, or does this translate into front end queries as well? Also, do you post your snippets on Gist?

    1. blobaugh (July 12, 2012)

      Yes Jeff, this is for the back end only. It taps into the query for listing the posts, and I am going to assume the query is different enough on the front that it probably will not work. Try it though and if I am wrong let me know 🙂

      Nope, my snippets are my own, sorry nothing on gist