如何在自定义登录表单中检索wp错误

2022-08-30 23:34:04

我已经在功能的帮助下创建了登录模板。现在,如果用户输入错误的密码或用户名,它将使用以下代码将我重定向到带有参数的同一页面:wp_login_form()login=failed

add_action( 'wp_login_failed', 'front_end_login_fail' );
function front_end_login_fail( $username ) {

$_SESSION['uname'] =  $username;
// Getting URL of the login page
$referrer = $_SERVER['HTTP_REFERER'];    
$login_failed_error_codes = array( 'empty_password', 'empty_email', 'invalid_email', 'invalidcombo', 'empty_username', 'invalid_username', 'incorrect_password' );

// if there's a valid referrer, and it's not the default log-in screen
if( !empty( $referrer ) && !strstr( $referrer,'wp-login' ) && !strstr( $referrer,'wp-admin' ) ) {
    wp_redirect( get_permalink( 93 ) . "?login=failed" ); 
    exit;
}

}

现在这个函数工作正常,但现在根据wordpress功能提供如下:

1.如果用户输入了真实的用户名,但密码错误,则会显示错误为“incorrect_password”

2.如果用户输入错误的用户名但正确的密码,它将显示错误为“invalid_username”

3.如果用户输入了错误的用户名但密码错误,则会将错误显示为“invalidcombo”

添加等,请检查变量$login_failed_error_codes in code...我做了一些搜索。我得到了一个名为“WP_error”的课程。但我不知道它是如何与这段代码一起工作的。

我只是陷入了如何将WP_error的对象从wp-login.php传递到我的csutom模板?

谢谢。。。任何帮助都是可以理解的。


答案 1

我想我明白你想要实现的目标。您希望能够在自己的自定义登录页面上显示登录失败的原因。我假设您已经知道如何获取参数,因为您正在使用它来传递参数。$_GETlogin_failed

请改用过滤器:login_redirect

add_filter('login_redirect', 'my_login_redirect', 10, 3);
function my_login_redirect($redirect_to, $requested_redirect_to, $user) {
    if (is_wp_error($user)) {
        //Login failed, find out why...
        $error_types = array_keys($user->errors);
        //Error type seems to be empty if none of the fields are filled out
        $error_type = 'both_empty';
        //Otherwise just get the first error (as far as I know there
        //will only ever be one)
        if (is_array($error_types) && !empty($error_types)) {
            $error_type = $error_types[0];
        }
        wp_redirect( get_permalink( 93 ) . "?login=failed&reason=" . $error_type ); 
        exit;
    } else {
        //Login OK - redirect to another page?
        return home_url();
    }
}

答案 2

如果您已经创建了用于登录的自定义模板,那么为什么不在自定义表单的帮助下使用wp_signon方法?它将返回WP_error个对象,如果为 false,它将返回$user对象。

<?php
if(isset($_POST['submit'])){
        $creds = array();
        $creds['user_login'] = $_POST['user_email'];
        $creds['user_password'] = $_POST['user_password'];
        $creds['remember'] = true;
        $user = wp_signon( $creds, false );
        if ( is_wp_error($user) )
            echo $user->get_error_message();
}
?>

<form id="user-credentials" method="post" action="<?php the_permalink(); ?>">
    <p><input name="user_email" type="text" placeholder="Email" /></p>
    <p><input name="user_password" type="password" placeholder="Password" /></p>
    <p><input type="submit" value="Submit" /></p>
</form>

我还没有测试过,但它应该有效。


推荐