0

can someone please help me with this query:

$ultimousuario = $wpdb->get_var( "SELECT TOP 1 FROM  $wpdb->users WHERE user_login = 'usuario*' ORDER BY user_login DESC");
echo "<p>O último usuário é {$ultimousuario}</p>";

We're trying to get the last user that contains "usuario*" at it's user_login, order by decrescent.

4
  • What do you mean by "last"? Most recently created, most recently logged in, ...? user_login is WordPress's term for "username", so ordering by that will just get you the username that's deepest in the alphabet.
    – Pat J
    Jul 29, 2021 at 15:48
  • 1
    If you are trying to get the user_login that's deepest in the alphabet starting with usuario (ie, if you have usuarioAAA and usuarioZZZ, and you want usuarioZZZ), then try changing WHERE user_login='ususario*' to WHERE user_login LIKE 'usuario%'.
    – Pat J
    Jul 29, 2021 at 15:52
  • I mean the last created, sorry. Jul 29, 2021 at 15:57
  • 2
    is there a reason you're using raw SQL instead of the built in functions and classes?
    – Tom J Nowell
    Jul 29, 2021 at 16:13

1 Answer 1

4

If you're trying to get the last user created with the username format usuario*, I'd recommend using get_users() instead of writing a SQL query.

$args = array(
    "search"         => "usuario*",            // Search string
    "search_columns" => array( "user_login" ), // Field(s) to search
    "order"          => "DESC",                // Search order
    "orderby"        => "user_registered",     // Order by this
    "number"         => 1,                     // Get only this many users
);
$user_objects = get_users( $args );
// Ensure we've got results
if ( ! empty( $user_objects ) ) {
    // Pull the 1st array element, which will be a WP_User object,
    // and use the get() method to extract the username to a variable
    $most_recent_usuario = $user_objects[0]->get( 'login_name' );
}
echo "<p>O último usuário é {$most_recent_usuario}</p>";

References

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.