Categories
Code Snippets WordPress

How To Change The Order of Custom Post Type On Admin Edit Screen

I have been working on a new plugin that utilizes the new Gutenberg, blocks editor. I wanted to change the order of the custom posts on the edit screen so that they are not ordered by name, as shown below.

Ordered By Name

 

Since the posts on the edit screen are displayed from wp_query I filtered pre_get_posts to set ‘orderby’ to date as shown below. To prevent all posts to be changed I only modify the query if it is one of my custom post types.

 

function ptc_admin_order( $wp_query ) {
  if (is_admin()) {
    $post_type = $wp_query->query['post_type'];

    if ( $post_type == 'ptc_clients' || $post_type == 'ptc_proposals' ) {
      $wp_query->set('orderby', 'date');

      
    }
  }
}
add_filter('pre_get_posts', 'ptc_admin_order');

 

This ordered the post by date, but in Ascending order.

Order By Date

I could easily sort the posts from the date column but I wanted to have them in descending order by default. So I set ‘order’ to desc.

/*
 * Change order of custom post type on admin edit.php screen from name to date
 * https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts
 */

function ptc_admin_order( $wp_query ) {
  if (is_admin()) {
    $post_type = $wp_query->query['post_type'];

    if ( $post_type == 'ptc_clients' || $post_type == 'ptc_proposals' ) {
      $wp_query->set('orderby', 'date');

      //If you set the order to desc the colun is not sortable
      $wp_query->set('order', 'DESC');
    }
  }
}
add_filter('pre_get_posts', 'ptc_admin_order');

They are in descending order by default but you can not use the column sort to display the posts in the reverse order.

Subscribe To Updates and Tips Via Email

Get tips on web development, WordPress, web design & more