WP User Query get all authors with last name starting with specific letter

The problem is that you can’t use the value for the LIKE comparison as you’ve mentioned. The generated SQL will look something along the lines of:

AND CAST(wp_usermeta.meta_value AS CHAR) LIKE '%B%'

which means that the query is set to look for every occurrence of letter B in our case. Of course this is not what you want, what you would need is something like this:

AND CAST(wp_usermeta.meta_value AS CHAR) LIKE 'B%'

so that the search will be done only starting with the B letter.

The good news is that you can still achieve what you need but with the cost of looking a bit like a hack. 🙂

The WP_User_Query:

$args = array(
    'meta_key'      => 'last_name',
    'meta_value'    => 'B########', // The '########' sequence acts sort of like an unique identifier
    'meta_compare'  => 'LIKE',
);

$wt_user_query = new WP_User_Query( $args );

And in functions.php we hook to the get_meta_sql filter and alter the WHERE clause:

function wt_custom_meta_sql( $sql ) {
    /* 
        Search for that funky so called unique identifier
        that we used to initialize our `WP_User_Query' object    
    */
    $uid = '########';
    preg_match( "https://wordpress.stackexchange.com/"(%[^']+{$uid}%)"https://wordpress.stackexchange.com/", $sql['where'], $matches );

    if ( ! empty( $matches ) ) {
        /* 
            We've found it and now we get rid of the
            extra '%' character as well as our identifier               
        */
        $val = str_replace( "{$uid}%", "%", ltrim( $matches[1], '%' ) );
        $sql['where'] = str_replace( $matches[0], "'{$val}'", $sql['where'] );
    }

    return $sql;
}
add_filter( 'get_meta_sql' , 'wt_custom_meta_sql', 40 );