您可能想结帐wp_signon 因为该功能可以提供WP_Error 对象,并在登录失败时显示相应的错误消息。。唯一的缺点是您必须创建自己的表单或根据需要替换操作url。
基本登录功能可以这样实现:
if (!function_exists(\'custom_login_function\')) {
/**
* Attempts to login a user via POST request.
*
* @return boolean
*/
function custom_login_function()
{
if (is_user_logged_in()) {
throw new \\Exception(__(\'User is already logged in.\'), 303);
}
$fields = array(
\'nonce\' => \'login_nonce\',
\'user_login\' => \'log\',
\'user_password\' => \'pwd\',
\'remember\' => \'remember_me\'
);
if (!wp_verify_nonce($fields[\'nonce\'], $fields[\'nonce\'])) {
throw new \\Exception(__(\'Invalid nonce.\'), 401);
}
$credentials = array();
array_walk($fields, function(&$field, $key) use ($credentials) {
if (!empty($_POST[$field])) {
$credentials[$key] = esc_sql($_POST[$field]);
}
});
$login_status = wp_signon($credentials, is_ssl());
if (is_wp_error($login_status)) {
throw new \\Exception($login_status->get_error_message(), 401);
}
return true;
}
}
然后,您可以这样使用它:
if (isset($_POST[\'log\'], $_POST[\'pwd\'])) {
try {
custom_login_function();
$redirect = !empty($_POST[\'redirect_to\'] ? $_POST[\'redirect_to\'] : home_url());
wp_safe_redirect($redirect);
} catch (\\Exception $error) {
$login_error = $error->getMessage();
}
}
$login_error 然后将包含函数或Wordpress在登录失败时引发的错误消息。
请注意,上面的函数还检查nonce. 默认情况下,这不会在Wordpress登录表单中实现,但您可以通过简单的函数调用将其添加到自定义表单中:
<?php wp_nonce_field(\'login_nonce\', \'login_nonce\'); ?>
这将插入一个名为“login\\u nonce”的隐藏字段。
顺致敬意,