Taxonomy terms sort by… Last name!

You can try the MySQL function SUBSTRING_INDEX() within the get_terms_orderby filter:

/**
 * Order by the last word in the term name
 * @link https://wordpress.stackexchange.com/a/195039/26350
 */
add_filter( 'get_terms_orderby', function( $orderby, $args )
{
    if( isset( $args['orderby'] ) && 'wpse_last_word' === $args['orderby'] )  
        $orderby = " SUBSTRING_INDEX( t.name, ' ', -1 ) ";
    return $orderby;
}, 10, 2 );

to order by the last word in the term name.

Here we activate the last-word ordering through our custom wpse_last_word argument:

$terms = get_terms( 'category', [ 'orderby' => 'wpse_last_word' ] );

You can also add the wpse_last_word argument, through the get_terms_args filter, if you need to override some term query.

I recently used this method here for posts.

Leave a Comment