在wordpress中使用add_action传递参数!
问题描述:
我有我的wordpress发展的一个非常奇怪的问题,在wordpress中使用add_action传递参数!
在fucntions.php我有以下代码
//mytheme/functions.php
$arg = "HELP ME";
add_action('admin_menu', 'my_function', 10, 1);
do_action('admin_menu',$arg);
function my_function($arg)
{
echo "the var is:".$arg."<br>";
}
输出
the var is:HELP ME
the var is:
为什么功能重复2次?为什么“帮助我”的论点被正确地传递并且第二次没有通过?
我一直在尽全力为期2天,并在很多地方搜索以找到解决方案,但我没有运气。
我想要做的事情很简单!我只想使用add_action将参数传递给函数?
答
Inside “的创建my_function”(尽管这是你的:)),写行:
print_r(debug_backtrace());
http://php.net/manual/en/function.debug-backtrace.php
它会帮助你知道,什么事。
或者,您可以使用XDebug(在开发服务器上)。
答
首先,在你的my_function()函数中,你不是,它定义了 $ arg。你试图回应那些不存在的东西 - 所以当它返回时,它是空的。所以你需要定义它。 (编辑补充:你试图定义它的功能之外 - 反而使内承认它,你必须全球化参数的函数类型。)
function my_function($arg) {
if(!$arg) $arg = 'some value';
echo "the var is:".$arg."<br>";
}
当你ADD_ACTION,你需要定义$ arg值:
add_action('admin_menu', 'my_function', 10, 'my value');
答
您是否试图在add_action之前放置函数?
答
可以使用匿名函数是这样的:
function my_function($arg) {
echo "the var is: $arg<br>";
}
$arg = "HELP ME";
add_action('admin_menu', function() { global $arg; my_function($arg); }, 10);
详见this answer。
add_action? do_action?它是什么? – 2011-04-27 07:29:12
@OZ_:这些是一些WordPress预定义函数,请参阅http://codex.wordpress.org/Function_Reference/add_action,谢谢 – ahmed 2011-04-27 09:31:55