how to filter by last name for custom post

Order by the last word in the post title

To order by the speaker’s last name, you can use the following setup (PHP 5.4+):

// args  
$args = [
    'posts_per_page'   => 10,
    'post_type'        => 'speaker',
    'meta_key'         => 'speaker-front-page',
    'meta_value'       => '1',
    'orderby'          => 'wpse_last_word',          //<-- Our custom ordering!
    'order'            => 'ASC'
];

// query
$the_query = new WP_Query( $args );

where the 'wpse_last_word' input is supported by the following:

/**
 * Order posts by the last word in the post_title. 
 * Activated when orderby is 'wpse_last_word' 
 * @link https://wordpress.stackexchange.com/a/198624/26350
 */
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 );

This is based on my answer here on ordering terms by the last word.

Leave a Comment