Leave a Reply

2 comments

  1. Something like this should work:

    function wpa84258_admin_posts_sort_last_name( $query ){
        global $pagenow;
        if( is_admin()
            && 'edit.php' == $pagenow
            && !isset( $_GET['orderby'] )
            && !isset( $_GET['post_type'] ) ){
                $query->set( 'meta_key', 'last_name' );
                $query->set( 'orderby', 'meta_value' );
                $query->set( 'order', 'ASC' );
        }
    }
    add_action( 'pre_get_posts', 'wpa84258_admin_posts_sort_last_name' );
    
  2. Instead of relying on the $_GET variables, the orderby value is also passed in the $query class itself. So you could also write it like this:

    add_action('pre_get_posts', function($query) {
        if ($query->query['orderby'] == "actor-last-name") {
            $query->set('meta_key', 'actor-last-name');
            $query->set('orderby', 'meta_value');
        }
    });