我有一个自定义注册表单,它使用admin_post_ {action}挂钩调用一个函数来完成对表单的所有处理。 functions.php文件包含类似这样的函数。
<?php
$example = 'test';
function create_client_account(){
//check username isn't a duplicate
//check email isn't a duplicate
//scrub all data
//create an array of errors
if($errors){
global $example
echo $example //outputs 'test'
$example = new WP_Error();
$example->add('test',$errors);
var_dump($example) //outputs WP_Error object
}
}
add_action( 'admin_post_create_account', 'create_client_account' );
add_action( 'admin_post_nopriv_create_account', 'create_client_account' );
?>
然后我有一个模板文件page-register.php,我尝试访问全局变量,但它不起作用。所有处理都是正确的,如果我在函数中执行var_dump($example)
,则所有输出都在那里。但是,如果我在模板文件中执行此操作,则输出为NULL。
<?php
global $example;
var_dump($example); //outputs 'test'
?>
我已经将问题确定为范围问题,在执行该功能后该全局不再可用,我相信这是由于操作挂钩但我不确定。
我的问题是如何让这项工作成功?如何在功能之外使全局可用。
答案 0 :(得分:0)
首先,您需要在函数范围之外定义变量:
<?php
$example = 0;
function create_client_account(){
//check username isn't a duplicate
//check email isn't a duplicate
//scrub all data
//create an array of errors
if($errors){//you should set and assign this $errors somewhere too
$GLOBALS['example'] = new WP_Error();
$GLOBALS['example']->add('test',$errors);
}
}
然后尝试像之前那样访问它
<?php
global $example;
var_dump($example);
?>