WordPress Orderby Last Word In Title
Try this. First add the following orderby filter in functions.php
function posts_orderby_lastname ($orderby_statement) { $orderby_statement = "RIGHT(post_title, LOCATE(' ', REVERSE(post_title)) - 1) DESC"; return $orderby_statement;}
and then use it in your query like so
add_filter( 'posts_orderby' , 'posts_orderby_lastname' ); $loop = new WP_Query( array ( 'post_type' => 'staff', 'staff-type' => $type ) );
and after the loop remove the filter
remove_filter( 'posts_orderby' , 'posts_orderby_lastname' );
The answer posted above is great. But there is an issue if the person in the list goes by only a single name. For example, Kanye would appear at the top of the results and not get sorted with the Ks.
I've updated the code and this will alphabetize those with just a single name as well as those with a first and last name. So Kanye will now appear with the Ks.
function posts_orderby_lastname ($orderby_statement) { $orderby_statement = "RIGHT(post_title, LOCATE(' ', CONCAT(REVERSE(post_title), ' ')) - 1) ASC"; return $orderby_statement;}