Custom Post type sort order not working in the admin area

The ‘title’ and ‘date’ columns are WordPress default tables (even for CPTs) so they should be automatically sortable, unless those columns have been replaced.

For custom columns there is a hook for registering a column as ‘sortable’: https://developer.wordpress.org/reference/hooks/manage_this-screen-id_sortable_columns/

//Filter is 'manage_edit-{custom post type}_sortable_columns
//or more generally 'manage_{screen id}_sortable_columns
add_filter( 'manage_edit-cpt_sortable_columns', 'wpse221267_cpt_sortable_columns' );
function wpse221267_cpt_sortable_columns( $columns ) {
    //$columns is an array indexed by column identifier
    //and the value is a sort identifier. This sets the orderby parameter (see below)
    //Each element in $columns corresponds to a sortable column
    $columns['column_id'] = 'sort_identifier';
    return $columns;
}

However, this only handles the user interface: it doesn’t actually implement the sort. To do that you would need to intercept the query at pre_get_posts:

add_action( 'pre_get_posts', 'wpse221267_column_orderby' );  
function wpse221267_column_orderby( $query ) {  

    //Some sanity checking, you may want to check for screen ID too.        
    if( ! is_admin() ) {
        return;  
    }

    //This value will be determined by the column clicked
    //and its associated sort identifier (see above!)
    $orderby = $query->get( 'orderby');  
    $order   = $query->get( 'order' );

    if( 'sort_identifier' == $orderby ) {  
        //Modify $query to sort by $orderby and $order.
    }  
}  

Leave a Comment