Sort Staff Posts by Last Name
If you are adding staff members where the post titles follow a First Name Last Name format and you would like to sort them alphabetically by last name, WordPress does not provide a built-in orderby option for this.
By default, WordPress can sort posts by the full title, date, menu order, and other standard fields, but it cannot sort by a specific part of the title (such as the last word in a staff member's name). The following snippet adds support for sorting staff post type queries by the last name extracted from the post title.
This is useful for staff directories where names are stored as the post title and you want the listing to display alphabetically by surname without needing to create and maintain a separate last name field.
add_filter( 'posts_orderby', function( $orderby, $query ) {
// Only affect frontend and theme AJAX requests.
if ( is_admin() && ! ( function_exists( 'vcex_doing_ajax' ) && vcex_doing_ajax() ) ) {
return $orderby;
}
// Target staff post type queries only.
$post_type = $query->get( 'post_type' );
if ( 'staff' !== $post_type
&& ( ! is_array( $post_type )
|| 1 !== count( $post_type )
|| 'staff' !== reset( $post_type )
)
) {
return $orderby;
}
// Respect explicit orderby values other than the default date ordering.
if ( $query->get( 'orderby' ) && 'date' !== $query->get( 'orderby' ) ) {
return $orderby;
}
global $wpdb;
return "SUBSTRING_INDEX({$wpdb->posts}.post_title, ' ', -1) ASC,
{$wpdb->posts}.post_title ASC";
}, 99, 2 );All PHP snippets should be added via child theme's functions.php file or via a plugin.
We recommend Code Snippets (100% Free) or WPCode (sponsored)
We recommend Code Snippets (100% Free) or WPCode (sponsored)
Related Snippets