3

I have a WordPress site that has a couple of custom post types. None of these custom post types allow me to sort the posts alphabetically or by date in the admin area.

I have looked all over online to try and work this out but I can't seem to find anything that works.

Do I need to apply an action on load of posts in the admin area?

1
  • Is working If you access the link direclty? something like wp-admin/edit.php?post_type=[your_post_type]&orderby=title&order=asc. If you click the table header is the page not being refreshed? If this is the case did you try with javascript disabled? Did you try 'Right click + open in new tab' ?
    – Pabamato
    Aug 14, 2018 at 5:12

1 Answer 1

2

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.
    }  
}  
1
  • Hey @Stephen Harris, Yeah I thought that would be case and I can even click the date and titles sort buttons in the header of the table. But when I click them it won't sort them. Is there anything else that could be causing this issue? Could be a plugin issue? Also I can still order the posts and pages. Mar 21, 2016 at 11:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.