Ask your WordPress questions! Pay money and get answers fast! (more info)

Sorting by second word unless only one word WordPress


I need to sort items in a query by the second word of the title (last name) unless there is only one word, then I need to sort by first name instead.

I added this to my functions file and called it in the query with a filter:

function posts_orderby_lastname ($orderby_statement)
$orderby_statement = "RIGHT(post_title, LOCATE(' ', REVERSE(post_title)) - 1) ASC";
return $orderby_statement;

add_filter( 'posts_orderby' , 'posts_orderby_lastname' );
'post_type' => 'artists',
'showposts' => -1,
'order' => 'ASC'
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
while ($my_query->have_posts()) : $my_query->the_post();
<div class="block item">
<a href="<?php the_permalink(); ?>">
<div class="inner">
<?php if ( has_post_thumbnail() ) { the_post_thumbnail(); } ?>
<div class="block-content">
<h4><?php the_title(); ?></h4>

remove_filter( 'posts_orderby' , 'posts_orderby_lastname' );
wp_reset_query(); // Restore global post data stomped by the_post().

It works fine for sorting by second word, but I've got a few words that are like "D'something" or "SomeThing" and these I need to sort by the first word, but they are sorting by the second, ie. "something" and "Thing".

I also tried to modify the third answer on [[LINK href=""]]this page[[/LINK]] to check if the if the string has no spaces in it, and if so to then sort by first word, but I had no clue how to modify it properly.

Variations on either of the above solutions would be great or if you've got a better way I'd be glad to use that, too.


Answers (1)


Dbranes answers:

You can try something like this (untested):

function posts_orderby_lastname ($orderby_statement)
return "
WHEN LOCATE(' ', REVERSE(post_title)) > 0 THEN RIGHT(post_title, LOCATE(' ', REVERSE(post_title)) - 1)
ELSE post_title

or some adjustments to this.

Mike Sewell comments:

That worked exactly as it was, thanks!