连接到“身份验证”会导致登录在页面加载时提交

时间:2021-09-14 作者:Victor

我为“Autneticate”钩子添加了一个过滤器,以应用一些额外的登录验证,但如果我将过滤器优先级更改为20,则即使表单未提交,过滤器似乎也会在wp登录页面加载时启动。

add_filter( \'authenticate\', \'custom_login\', 20, 3 );
无论何时加载登录页面,即使未提交任何内容,也始终显示此消息:

ERROR: Empty username or password.
由于这是“custom\\u login”功能中的第一次签入:

        if($username == \'\' || $password == \'\') {
    
            $error = new WP_Error();

            $error->add(\'empty_username\', __(\'<strong>ERROR</strong>: Empty username or password.\'));
        
            return $error;
    }
我试图理解为什么即使表单没有在wp登录页面加载时提交,它也会运行。

1 个回复
SO网友:Sally CJ

I am trying to understand why it runs even if the form is not submitted on wp-login page load.

That\'s just how it works.

If the current action is login which is the default action, then wp_signon() is always called on page load regardless the login form was submitted or not, and thus your function runs because wp_signon() calls wp_authenticate() which fires the authenticate hook.

So yes, this is an expected behavior:

Any time, the login page is loaded, this message is always displayed even though nothing is submitted

But it can be prevented.

First, set your callback priority to 20, and secondly, check if the $user (the first parameter) is already a WP_Error instance and if so, then simply return the instance. E.g.

add_filter( \'authenticate\', \'custom_login\', 20, 3 ); // set priority to 20 or more
function custom_login( $user, $username, $password ) {
    // The user might already be authenticated, so return the user object.
    if ( $user instanceof WP_User ) {
        return $user;
    }

    // There\'s already an error authenticating the user, or maybe the user
    // has just landed on the login page, so just return the error object.
    if ( is_wp_error( $user ) ) {
        return $user;
    }

    // ... your validation/code here.

    return $user;
}

And I thought it might be worth quoting this from the filter documentation:

The wp_authenticate_user filter can also be used if you want to perform any additional validation after WordPress’s basic validation, but before a user is logged in.

The default authenticate filters in /wp-includes/default-filters.php

add_filter( \'authenticate\', \'wp_authenticate_username_password\',  20, 3 );
add_filter( \'authenticate\', \'wp_authenticate_email_password\',     20, 3 );
add_filter( \'authenticate\', \'wp_authenticate_spam_check\',         99    );

See wp_authenticate_username_password(), wp_authenticate_email_password() and wp_authenticate_spam_check() for details about what the functions do.

相关推荐

WordPress摘录-如何使用unctions.php删除第一个链接

我刚刚将一个博客导入Wordpress,所有内容都以以下内容开头:<a href="itunes.com">Listen on iTunes</a> 然后是段落内容,因此所有节选都显示为“;收听iTunes内容摘录"E;我尝试了这里的一些自定义函数,但似乎没有一个能起到作用。在不必移动iTunes链接的情况下删除Listen on iTunes文本的最佳方法是什么?例如,我试过这个。。。没有运气。。。 function custom_ex