钩子文档

login_errors

💡 云策文档标注

概述

login_errors 是一个 WordPress 过滤器,用于自定义登录表单上方显示的错误消息。开发者可以通过此 Hook 修改或移除默认的错误信息,以增强用户体验或调整安全策略。

关键要点

  • login_errors 过滤器允许修改登录错误消息,参数为错误消息字符串。
  • 该过滤器在 login_header() 函数中被调用,位于 wp-login.php 文件中。
  • 自 WordPress 2.1.0 版本引入,是核心登录系统的一部分。

代码示例

add_filter( 'login_errors', function( $error ) {
    global $errors;
    $err_codes = $errors->get_error_codes();

    // Invalid username.
    // Default: 'ERROR: Invalid username. Lost your password?'
    if ( in_array( 'invalid_username', $err_codes ) ) {
        $error = 'ERROR: Invalid username.';
    }

    // Incorrect password.
    // Default: 'ERROR: The password you entered for the username %1$s is incorrect. Lost your password?'
    if ( in_array( 'incorrect_password', $err_codes ) ) {
        $error = 'ERROR: The password you entered is incorrect.';
    }

    return $error;
} );

注意事项

  • 示例代码中使用了全局变量 $errors,需确保其在上下文中正确初始化,否则可能引发异常(如 Call to a member function get_error_codes() on null)。
  • 开发者应谨慎处理错误消息,避免泄露敏感信息或影响安全性。

📄 原文内容

Filters the error messages displayed above the login form.

Parameters

$errorsstring
Login error messages.

Source

$errors = apply_filters( 'login_errors', $errors );

Changelog

Version Description
2.1.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    Example migrated from Codex:

    The following callback removes the ‘password reminder’ link from the two main login error messages.

    add_filter( 'login_errors', function( $error ) {
    	global $errors;
    	$err_codes = $errors->get_error_codes();
    
    	// Invalid username.
    	// Default: '<strong>ERROR</strong>: Invalid username. <a href="%s">Lost your password</a>?'
    	if ( in_array( 'invalid_username', $err_codes ) ) {
    		$error = '<strong>ERROR</strong>: Invalid username.';
    	}
    
    	// Incorrect password.
    	// Default: '<strong>ERROR</strong>: The password you entered for the username <strong>%1$s</strong> is incorrect. <a href="%2$s">Lost your password</a>?'
    	if ( in_array( 'incorrect_password', $err_codes ) ) {
    		$error = '<strong>ERROR</strong>: The password you entered is incorrect.';
    	}
    
    	return $error;
    } );