saronstar
saronstar

Reputation: 1

Wordpress : how to search a user by username in wordpress

I am trying to do an {Ask for a challange } button under online games posts in WordPress, so the user will choose another user form a search box and send a request for it with the link of the game,but I have no idea how to do this,

so as a start I tried this code so it can show me if the search method works or not but it didn't, also it is my first time to create a search box so .. here it is:

<?php 
 global $wpdb ;
if($_POST){

    $search_input = $_POST['chs'];
    if(username_exists($search_input)){
        print_r($search_input)  ;

    }else {
        print_r("there is no username by this");
    }
}

?>

<html>
    <head>

    </head>
    <body>
        <form method="post">
            <p> would you challenge your friends ? </p>
            <input type="text" name="chs" id="chs" >
            <button type="submit"> Challenge</button>
        </form>

    </body>

</html>

in this code I want it to return the searched username if it is existed, but then I need to return suggestions of usernames that could match the entries. ex: if the user is typing "mf" it will return the best suggestions of usernames according to what the user types and then the user choose from them.

Upvotes: 0

Views: 363

Answers (1)

Sagar Bahadur Tamang
Sagar Bahadur Tamang

Reputation: 2709

You can use the get_user_by() to get the User information by username

<?php
$user = get_user_by( 'login', $username);

if ( $user !== false){
   // User with the username is found. Do your work
} else {
   // User with the username is not found.
}
?>

Reference: https://developer.wordpress.org/reference/functions/get_user_by/

Upvotes: 1

Related Questions