用户登录后需要获取用户ID

时间:2020-12-28 作者:Rubicon14

当前正在运行wordpress 5.6

我涉猎PHP很长时间了,但对修改wordpress还是新手。如果满足某些条件,我最终会在用户登录后立即为用户修改数据库。为此,我希望在用户登录后立即获得用户ID。我尝试使用默认的wordpress add\\u操作(“wp\\u登录”,“test\\u邮件”);据我所知,这应该在用户登录wordpress后执行。

当用户登录并收到电子邮件,但我的用户ID始终为0时,以下函数将按预期启动。我得忽略一些简单的建议。

function test_mail(){
    $user = wp_get_current_user();
    $message .= "CURRENT USER ID: " . $user->ID . "\\n";
        
    $to = "admin@xxxxxxxxxx.com";
    $subject = "Testing mail from login";
    $header = "";
    $attachments  = "";
    wp_mail( $to, $subject, $message, $headers, $attachments );         
}

add_action(\'wp_login\', \'test_mail\');

1 个回复
最合适的回答,由SO网友:Q Studio 整理而成

wp\\u login传递了两个参数,但您需要更新挂钩才能将它们正确传递给函数:

function test_mail( $user_login, $user ) {
    //$user = wp_get_current_user();
    $message .= "CURRENT USER ID: " . $user->ID . "\\n";
        
    $to = "admin@xxxxxxxxxx.com";
    $subject = "Testing mail from login";
    $header = "";
    $attachments  = "";
    wp_mail( $to, $subject, $message, $headers, $attachments );      
}
add_action(\'wp_login\', \'test_mail\', 10, 2);
请在此处阅读更多信息:https://developer.wordpress.org/reference/hooks/wp_login/

相关推荐