1

I have a CPT - Author where the title of the post is used as Author's name. I'm trying to list the authors alphabetically based on the last word (last name) and it works best.

Here is the code in the functions.php

add_filter( 'posts_orderby', function( $orderby, \WP_Query $q )
{
if( 'wpse_last_word' === $q->get( 'orderby' ) && $get_order =  $q->get( 'order' ) )
{
    if( in_array( strtoupper( $get_order ), ['ASC', 'DESC'] ) )
    {
        global $wpdb;
        $orderby = " SUBSTRING_INDEX( {$wpdb->posts}.post_title, ' ', -1 ) " . $get_order;
    }
}
return $orderby;
}, PHP_INT_MAX, 2 ); 

And to sort them, I use below code just before the query

add_filter( 'posts_orderby' , 'posts_orderby_lastname' );

My problem is when two Authors have the same last name. I want to still list them alphabetically on the second last word or the 3rd last word if the last/second last word is the same. E.g.

James Lucas
George Lucas

It currently lists the Authors based on the published date in case the last names are same.

How to list based on second last or third last word?

4
  • this was answered here: wordpress.stackexchange.com/questions/198610/…
    – rudtek
    Commented Jan 21, 2019 at 15:52
  • The referenced answer doesn't seem to address my problem. I'm in fact using the same code and it works great as long as the last name is not the same. The above solution fails to sort when two or more authors have the same last name. So, how to sort authors on their first name when their last name is same? Commented Jan 21, 2019 at 16:55
  • did you try the 2nd answer?
    – rudtek
    Commented Jan 21, 2019 at 16:56
  • Yes. I copied the second answer's code and replaced that in the functions.php for add_filter, but no effect. This is how the listing is coming for my authors - Anthony Luckas - Rachel Lucas - Barbara Lucas. Commented Jan 21, 2019 at 17:02

1 Answer 1

1

I think I got it!!!

Try this:

 $orderby = " SUBSTRING_INDEX( {$wpdb->posts}.post_title, ' ', -1 ) " . $get_order. " , {$wpdb->posts}.post_title " . $get_order;

Basically it's sorting by lastname and then first name in 1 query.

So, your whole code would be:

add_filter( 'posts_orderby', function( $orderby, \WP_Query $q )
{
if( 'wpse_last_word' === $q->get( 'orderby' ) && $get_order =  $q->get( 'order' ) )
{
    if( in_array( strtoupper( $get_order ), ['ASC', 'DESC'] ) )
    {
        global $wpdb;

       $orderby = " SUBSTRING_INDEX( {$wpdb->posts}.post_title, ' ', -1 ) " . $get_order. " , {$wpdb->posts}.post_title " . $get_order;
    }
}
return $orderby;
}, PHP_INT_MAX, 2 ); 
1
  • Can you check as the answer please? It's the checkmark to the left of the question under the vote number?
    – rudtek
    Commented Jan 23, 2019 at 15:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.