Skip to main content
2 of 3
added 253 characters in body
Michael Ecklund
  • 6.8k
  • 13
  • 68
  • 110

You can use this for setting default sort orders on post types.

/* Sort posts in wp_list_table by column in ascending or descending order. */
function custom_post_order($query){
    /* 
        Set post types.
        _builtin => true returns WordPress default post types. 
        _builtin => false returns custom registered post types. 
    */
    $post_types = get_post_types(array('_builtin' => true), 'names');
    /* The current post type. */
    $post_type = $query->get('post_type');
    /* Check post types. */
    if(in_array($post_type, $post_types)){
        /* Post Column: e.g. title */
        if($query->get('orderby') == ''){
            $query->set('orderby', 'title');
        }
        /* Post Order: ASC / DESC */
        if($query->get('order') == ''){
            $query->set('order', 'ASC');
        }
    }
}
if(is_admin()){
    add_action('pre_get_posts', 'custom_post_order');
}

You can use some of these example conditions...

/* Effects all post types in the array. */
if(in_array($post_type, $post_types)){
    
}

/* Effects only a specific post type in the array of post types. */
if(in_array($post_type, $post_types) && $post_type == 'your_post_type_name'){
    
}

/* Effects all post types in the array of post types, except a specific post type. */
if(in_array($post_type, $post_types) && $post_type != 'your_post_type_name'){
    
}

If you wanted to apply this sorting on ALL post types, regardless of whether or not they are "built-in"...

Change this: $post_types = get_post_types(array('_builtin' => true), 'names');

To this: $post_types = get_post_types('', 'names');

Michael Ecklund
  • 6.8k
  • 13
  • 68
  • 110