Using WordPress ‘login_init’ PHP action

The login_init WordPress PHP action fires when the login form is initialized, allowing you to perform custom actions during the login process.


add_action('login_init', 'my_custom_login_init');
function my_custom_login_init() {
    // your custom code here


  • None

More information

See WordPress Developer Resources: login_init


Redirect users to a custom login page

Create a custom login page and redirect users to it instead of the default WordPress login page.

add_action('login_init', 'my_custom_login_page_redirect');
function my_custom_login_page_redirect() {
    $custom_login_page = '';

Enforce SSL on the login page

Force users to log in using SSL (HTTPS) for added security.

add_action('login_init', 'force_ssl_login');
function force_ssl_login() {
    if (!is_ssl()) {
        wp_safe_redirect('https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], 301);

Add a custom error message to the login page

Display a custom error message on the login page when users enter incorrect credentials.

add_action('login_init', 'my_custom_login_error_message');
function my_custom_login_error_message() {
    if (isset($_GET['login']) && $_GET['login'] === 'failed') {
        add_filter('login_errors', function () {
            return 'Incorrect username or password. Please try again.';

Limit login attempts

Limit the number of login attempts to protect your site from brute force attacks.

add_action('login_init', 'limit_login_attempts');
function limit_login_attempts() {
    if (!session_id()) {

    if (isset($_SESSION['login_attempts']) && $_SESSION['login_attempts'] >= 5) {
        wp_die('Too many failed login attempts. Please try again later.');

Log IP addresses of failed login attempts

Log the IP addresses of users who fail to log in to help identify potential security threats.

add_action('wp_login_failed', 'log_failed_login_attempts');
function log_failed_login_attempts($username) {
    $ip_address = $_SERVER['REMOTE_ADDR'];
    $failed_logins = get_option('failed_login_attempts', array());
    $failed_logins[] = array('username' => $username, 'ip_address' => $ip_address, 'timestamp' => current_time('mysql'));
    update_option('failed_login_attempts', $failed_logins);

add_action('login_init', 'check_failed_login_attempts');
function check_failed_login_attempts() {
    if (isset($_GET['login']) && $_GET['login'] === 'failed') {
        add_action('wp_login_failed', 'log_failed_login_attempts');