Order posts of a custom post type by date DESC in wp-admin

If you are using / having a custom post type and you have a problem with the posts ordered ASC, you can use one of the codes below to make the order DESC by default.

function wpse_819391_post_types_admin_order( $wp_query ) {
  if ( is_admin() && !isset( $_GET['orderby'] ) ) {     
    // Get the post type from the query
    $post_type = $wp_query->query['post_type'];
    if ( in_array( $post_type, array('videos','news','text') ) ) {
      $wp_query->set('orderby', 'date');
      $wp_query->set('order', 'DESC');
    }
  }
}
add_filter('pre_get_posts', 'wpse_819391_post_types_admin_order');

This is a smarter code 😉

add_action('pre_get_posts', 'filter_posts_list'); 

    function filter_posts_list($query)  {
        //$pagenow holds the name of the current page being viewed
         global $pagenow, $typenow;  
        if(current_user_can('edit_posts') && ('edit.php' == $pagenow))  { 
            //global $query's set() method for setting
            $query->set('orderby', 'date');
            $query->set('order', 'desc');
        }
    }

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.