我正在客户网站的主题中构建一个自定义登录和注册表单,我需要将任何错误消息处理为一个变量,该变量可以显示在表单内的页面上。我正在为表单本身使用短代码,因此在呈现短代码后会执行“after\\u setup\\u theme”操作,这意味着我设置的任何变量都不能用于短代码本身。这也意味着在成功登录时,is_user_logged_in()已事先检查,因此它仍然认为该用户没有实际登录。
在“after\\u setup\\u theme”之前是否还有其他操作可用于处理登录并存储任何错误变量?
编辑:这里是处理登录和操作挂钩的自定义函数。目前,我在页面上打印并使用jQuery将其移动到表单中时出错,但我宁愿找到一个解决方案,允许我将其打印到它所属的位置,这样我就不必在加载时操纵DOM元素。
function custom_login() {
if(!is_admin() && !preg_match(\'*wp-login.php*\', $_SERVER[\'REQUEST_URI\'])) {
$username = isset($_POST[\'log\']) && strlen($_POST[\'log\']) ? $_POST[\'log\'] : \'\';
$password = isset($_POST[\'pwd\']) && strlen($_POST[\'pwd\']) ? $_POST[\'pwd\'] : \'\';
if(strlen($username)) {
$creds = array();
$creds[\'user_login\'] = $username;
$creds[\'user_password\'] = $password;
$creds[\'remember\'] = true;
$user = wp_signon($creds, false);
if (is_wp_error($user)) {
$login_error = \'<div style="display: none;" id="login-error">\'.$user->get_error_message().\'</div>\';
echo $login_error;
} else {
if(isset($_POST[\'redirect_to\']) && strlen($_POST[\'redirect_to\']) > 3) {
wp_redirect($_POST[\'redirect_to\']);
} else {
wp_redirect(home_url().\'/login/\');
}
}
}
}
}
// run it before the headers and cookies are sent
if(isset($_POST[\'frontend_login\'])) {
add_action(\'after_setup_theme\', \'custom_login\');
}
最合适的回答,由SO网友:s_ha_dum 整理而成
after_setup_theme
应该not 在短代码处理之后执行。短代码在帖子主体渲染时处理。after_setup_theme
在此之前运行良好。你对问题的分析不正确。
这看起来像variable scope 我有问题。您的custom_login
函数将在该函数外部可访问。它们的“范围”在函数内部。
要解决这个问题,需要声明变量global
或者将整个内容包装在一个类中,以便可以使用类语法访问变量。概念验证:
class test_class {
static $test = \'hi\';
public function change_var() {
static::$test = \'hello\';
}
}
add_action(\'after_setup_theme\',\'test_class::change_var\');
还有其他方法可以做到这一点。