Home » Hooks » wp_login

The WordPress hook wp_login is a powerful tool that allows developers to perform custom actions whenever a user logs in to their WordPress website. This hook is triggered right after a successful login attempt, making it an ideal point to execute additional code or modify specific functionalities.

The wp_login hook is particularly useful for tasks such as user tracking, user activity logging, user role management, and custom login notifications. By utilizing this hook, developers can enhance the user experience, implement custom login workflows, and integrate third-party services seamlessly.

Here’s an example usage code demonstrating how to use the wp_login hook:

function custom_login_actions($user_login, $user) {
    // Perform custom actions upon user login
    // For example, log user activity or send a custom notification

    // Log user activity
    $log_message = 'User ' . $user_login . ' logged in';

    // Send custom notification
    $notification_message = 'Welcome back, ' . $user_login . '! We're glad to see you.';
    wp_mail($user->user_email, 'Login Notification', $notification_message);
add_action('wp_login', 'custom_login_actions', 10, 2);

In this example, we have created a function called custom_login_actions that accepts two parameters: $user_login (the user’s login username) and $user (the WP_User object representing the logged-in user). Inside the function, we perform two custom actions. Firstly, we log the user’s login activity by generating a log message and writing it to the error log. Secondly, we send a personalized welcome email to the user’s registered email address.

By using the add_action function, we attach our custom_login_actions function to the wp_login hook with a priority of 10 and a parameter count of 2. This ensures that our custom actions are executed whenever a user successfully logs in.

By leveraging the wp_login hook, developers have the flexibility to extend and customize the login process according to the specific needs of their WordPress projects.

Learn More on WordPress.org

Register an account to save your snippets or go Pro to get more features.