Sort custom post types by last name in the backend

If you want to override the default- and the title ordering, and order instead by the last word in the title.

/**
 * Override default- and title ordering in the backend, for the 'speaker' custom post type.
 *
 * @link https://wordpress.stackexchange.com/a/202154/26350
 */
add_action( 'pre_get_posts', function( \WP_Query $q ) 
{
    if (  
            is_admin() 
         && $q->is_main_query() 
         && 'edit-speaker' === get_current_screen()->id 
         && ( '' === $q->get( 'orderby' ) || 'title' === $q->get( 'orderby' ) )
    ) {
        $q->set( 'orderby', 'wpse_last_word' );     
        $q->set( 'order', '' !== $q->get( 'order' ) ? $q->get( 'order' ) : 'ASC' );     
    }
} );

where we use the plugin from our last answer to support the wpse_last_word ordering.

Leave a Comment