currently running wordpress 5.6
Ive dabbled with PHP for a long time but new to modifying wordpress. Im ultimately looking to modify the database for a user right after a user logs in if certain conditions are met. To that end im looking to get the users ID right after they log in. Ive tried to make use of the default wordpress add_action(‘wp_login’, ‘test_mail’); which as I understand it is supposed to be performed after a user logs into wordpress.
The below function gets fired off as expected when a user logs in and I get the e-mail but my userid is always 0. Ive got to be overlooking something simple any suggestions.
function test_mail(){
$user = wp_get_current_user();
$message .= "CURRENT USER ID: " . $user->ID . "n";
$to = "<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0d6c696064634d75757575757575757575236e6260">[email protected]</a>";
$subject = "Testing mail from login";
$header = "";
$attachments = "";
wp_mail( $to, $subject, $message, $headers, $attachments );
}
add_action('wp_login', 'test_mail');
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
wp_login is passed two params, but you will need to update your hook to pass them correctly to your function:
function test_mail( $user_login, $user ) {
//$user = wp_get_current_user();
$message .= "CURRENT USER ID: " . $user->ID . "n";
$to = "[email protected]";
$subject = "Testing mail from login";
$header = "";
$attachments = "";
wp_mail( $to, $subject, $message, $headers, $attachments );
}
add_action('wp_login', 'test_mail', 10, 2);
Read more here: https://developer.wordpress.org/reference/hooks/wp_login/
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0