6

If I add a custom post type (example code below), in the admin page for the new custom post type the posts are sorted by ID by default. Is there a way to set the default sort order to the post title instead (only for this new custom post type)?

    $labels = array(
    'name' => 'States',
    'singular_name' => 'State',
    'add_new' => __( 'Add State' ),
    'add_new_item' => __( 'Add New State' ),
    'edit_item' => __( 'Edit State' ),
    'new_item' => __( 'New State'),
    'view' => __( 'View State'),
    'view_item' => __( 'View State'),
    'search_items' => __( 'Search States'),
    'not_found' => __( 'No States found' ),
    'not_found_in_trash' => __( 'No States found in trash' ),
    'parent' => __( 'Parent State')
);

$args = array('public' => true, 
              'show_ui' => true,
              'show_in_nav_menus' => true,
              'show_in_menu' => true,
              'labels' => $labels,
              'supports' => array( 'title','editor')
              );
register_post_type( 'states', $args );
9

You could force the order via pre_get_posts:

function wpa_order_states( $query ){
    if( !is_admin() )
        return;

    $screen = get_current_screen();
    if( 'edit' == $screen->base
    && 'states' == $screen->post_type
    && !isset( $_GET['orderby'] ) ){
        $query->set( 'orderby', 'title' );
        $query->set( 'order', 'ASC' );
    }
}
add_action( 'pre_get_posts', 'wpa_order_states' );
| improve this answer | |
3

I found this answer was better here (altered to suit question):

function se91124_order_post_type($query) {
  if($query->is_admin) {

        if ($query->get('post_type') == 'States')
        {
          $query->set('orderby', 'title');
          $query->set('order', 'ASC');
        }
  }
  return $query;
}
add_filter('pre_get_posts', 'se91124_order_post_type');

Please note that se91124_order_post_type can be changed to any function name, States is the post_type name or label, the orderby title can be anything you like (e.g. menu_order), and obviously ASC can be changed for DESC.

Original from URL:

function posts_for_current_author($query) {

  if($query->is_admin) {

        if ($query->get('post_type') == 'portfolio')
        {
          $query->set('orderby', 'menu_order');
          $query->set('order', 'ASC');
        }
  }
  return $query;
}
add_filter('pre_get_posts', 'posts_for_current_author');
| improve this answer | |

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.