WordPress Login Action Hook

August 2020 | John Binzak
After the very last action taken in the function when a user logs in, the wp_login action hook is triggered. See how you can benefit from using it.

What Are Hooks

In WordPress, are a way for one block of PHP code to interact with another block of code at specific, pre-defined spots. These pre-defined spots are typically with the WordPress Core code. They make up the foundation for how plugins and themes interact with WordPress.

There are 2 types of : Actions and Filters. Actions allow you modify how WordPress operates. Callback functions for Actions will typically perform a new or modify task, like saving to the database or sending a notification, at the specific hook execution.

Filters allow you to modify data during the execution of WordPress. So opposed to performing a new task, such as saving to the database, the callback function transform data and return it to WordPress.

WordPress simplifies the differences between the two as:

  • An action interrupts the code flow to do something, and then returns back to the normal flow without modifying anything.
  • A filter is used to modify something in a specific way so that the modification is then used by code later on.

Hook After User Logs In

After the very last action taken in the function when a user logs in, the action hook is triggered. Since this is an action hook, it is meant to primarily act as an event trigger opposed to filtering the login data.

This hook provides access to two arguments: $user->user_login (string) and $user (WP_User). We can access them via our hook callback after setting an action priority and the argument request count:

<?php
function your_custom_function( $user_login, $user ) {
    // your post login code
}
add_action('wp_login', 'your_custom_function', 10, 2);?>

Possible Use Cases

This hook can be very useful in many cases, here are a few possible ideas:

  • Analytics - Perhaps you want to store how frequent users log in for further analysis
  • Scheduling Tasks - Maybe you have a task of batch processing that you only want to start when a particular user log ins, this might cut costs on unneeded CPU
  • Notifications - There might be a reason to notify yourself or others based on which user log ins, perhaps prioritizing certain work

Summary

Overall this is a very straight forward action hook. Hopefully this article gives you some inspiration on not only how to use it, but also make your website better.