钩子文档

wp_login

💡 云策文档标注

概述

wp_login 是一个 WordPress 动作钩子,在用户成功登录后触发,通常用于执行登录后的自定义操作,如发送欢迎邮件或记录登录信息。

关键要点

  • 触发时机:在 wp_signon() 函数中,用户登录成功后立即触发,位于 wp_set_auth_cookie() 调用之后。
  • 参数:提供两个参数:$user_login(字符串,用户名)和 $user(WP_User 对象,登录用户对象)。
  • 使用方式:通过 add_action() 添加回调函数,需指定优先级(默认 10)和参数数量(2)。
  • 相关函数:与 wp_signon() 紧密关联,用于用户认证和登录。

代码示例

// 回调函数
function wpdocs_send_welcome_email( $user_login, WP_User $user ) {

    // 如果用户是管理员或已发送过欢迎邮件,则不发送
    if ( current_user_can( 'administrator' ) || get_user_meta( $user->ID, 'wpdocs_welcome_email_sent', TRUE ) ) {
        return;
    }

    // 发送欢迎邮件给首次登录用户
    $message = str_replace(
        array( '%%firstname%%', '%%name%%', '%%sitename%%' ),
        array(
            $user->first_name,
            $user->data->user_login,
            get_bloginfo( 'name' ),
        ),
        get_option( 'welcome_message' )
    );

    // 发送邮件
    if ( wp_mail( $user->data->user_email, 'Welcome subject', $message ) ) {
        // 更新用户元数据标记邮件已发送
        update_user_meta( $user->ID, 'wpdocs_welcome_email_sent', 1 );
    }

}

// 添加动作钩子
add_action( 'wp_login', 'wpdocs_send_welcome_email', 10, 2 );

📄 原文内容

Fires after the user has successfully logged in.

Parameters

$user_loginstring
Username.
$userWP_User
WP_User object of the logged-in user.

More Information

The wp_login action hook is triggered when a user logs in by the wp_signon() function. It is the very last action taken in the function, immediately following the wp_set_auth_cookie() call.

This hook provides access to two parameters: $user->user_login (string) and $user ( WP_User ). To pass them into your function you will need to add a priority (default is 10) and request 2 arguments from the add_action() call:

Source

do_action( 'wp_login', $user->user_login, $user );

Changelog

Version Description
1.5.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    Sending a welcome email to first time logged in users.

    // callback function
    function wpdocs_send_welcome_email( $user_login, WP_User $user ) {
    
        // do not send email if user has already logged in once
        if ( current_user_can( 'administrator' ) || get_user_meta( $user->ID, 'wpdocs_welcome_email_sent', TRUE ) ) {
            return;
        }
    
        // send welcome email if logging in first time
        $message = str_replace(
            array( '%%firstname%%', '%%name%%', '%%sitename%%' ),
            array(
                $user->first_name,
                $user->data->user_login,
                get_bloginfo( 'name' ),
            ),
            get_option( 'welcome_message' )
        );
    
        // send email to user
        if ( wp_mail( $user->data->user_email, 'Welcome subject', $message ) ) {
            // update or add user meta if email sent successfully
            update_user_meta( $user->ID, 'wpdocs_welcome_email_sent', 1 );
        }
    
    }
    
    // action hook
    add_action( 'wp_login', 'wpdocs_send_welcome_email', 10, 2 );