Joel Joel - 3 months ago 13
PHP Question

Can't access user details with get_user_by or wp_get_current_user function in WordPress on wp_login hook

I'm building a plugin which needs to get the user's name and email when they log in to a WordPress site. I've tried using both the

get_user_by()
and
wp_get_current_user()
functions in WordPress but to no avail. I'm using the
wp_login
action hook.

Example of code:

function send_login_notification()
{
$user_info = get_user_by('id', get_current_user_id());
$user_name = ucfirst($user_info->user_login);
$user_email = $user_info->user_email;

[...]

}

add_action('wp_login', 'send_login_notification');


However, I am presented with the following error sometimes, but not always:

Notice: Trying to get property of non-object in [file path] on line 48

Notice: Trying to get property of non-object in [file path] on line 49


If I refresh, chances are it will work, which is strange. It really is hit-and-miss.

Answer

I don't have experience of this particular hook, however it sounds like it uses a session / cookie to hold the user details. In which case your first call is happening before the session is created/available. However, on the refresh the session is available and the code works.

Have you tried setting the priority on your action to ensure is occurs as late as possible? Most events have a priority of 10 so setting your action somewhere after that will do the job.

add_action('wp_login', 'send_login_notification', 15, 2);

If that doesn't work, you should take a at the codex or here it indicates that you could authenticate the user yourself, then you can build the user data to manipulate for your own code.

$user = wp_authenticate($username, $password);

Hopefully, adding that line will make the difference.

It seems that neither of the above methods were sufficient to ensure that the login session was available to the script, so a small change to the function was required to make use of the data available to the function via wp_login.

function send_login_notification($username, $password)
{
    $user_info = get_user_by('login', $username);