admin管理员组

文章数量:1289525

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.

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.

Share Improve this question edited Jul 29, 2021 at 15:53 birgire 68k7 gold badges120 silver badges252 bronze badges asked Jul 29, 2021 at 15:25 Fernando MitsugiFernando Mitsugi 11 bronze badge 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 Commented 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 Commented Jul 29, 2021 at 15:52
  • I mean the last created, sorry. – Fernando Mitsugi Commented 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 Commented Jul 29, 2021 at 16:13
Add a comment  | 

1 Answer 1

Reset to default 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

  • get_users()
  • WP_User_Query::prepare_query() for the $args details
  • WP_User::get() to extract the user_login from the WP_User object

本文标签: How to get last user with wpdb