I have a custom Taxonomy named ‘authors’ where I insert additional authors.
My question is: is it possible to list all the taxonomy terms order by “Last Name”.
If I order by name clearly it looks like:
- Andrea Red
- Daniel Green
- Elena Blue
Instead of this I would like to sort by Last Name:
- Elena Blue
- Daniel Green
- Andrea Red
Do you have any advice to do it? Is it better to add a New Custom Field in Custom Taoxnomy where I specify the Last Name and then I sort by that term?
Thank you very much
Elena
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.