在 WordPress 中使用 add_action 传递参数!
我在 WordPress 开发中遇到了一个非常奇怪的问题,
在 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 次?为什么“help me”这个论点已经正确通过,而第二次却没有通过?
我已经尽力了两天,并在很多地方寻找解决方案,但我没有运气。
我想做的事情很简单!我只想使用 add_action 将参数传递给函数?
I have a very strange problem in my wordpress development,
in fucntions.php I have the following code
//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 output is
the var is:HELP ME
the var is:
Why the function repeated 2 times? Why has the argument "help me" been passed correctly and the 2nd time it havent been passed?
I have been trying all my best for 2 days and searched in many places to find a solution but I had no luck.
What I am trying to do is simple! I just want to pass argument to a function using add_action?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在“my_function”(尽管它是你的:))中,写入以下行:
http:// php.net/manual/en/function.debug-backtrace.php
它将帮助您了解正在发生的事情。
或者,您可以使用 XDebug (在开发服务器上)。
Inside "my_function" (albeit it's yours :)), write line:
http://php.net/manual/en/function.debug-backtrace.php
It will help you to know, what are going on.
Or, you can use XDebug (on development server).
好吧,首先,在 my_function() 函数中,您没有定义 $arg。你试图回显一些不存在的东西——所以当它返回时,它是空的。所以你需要定义它。 (编辑添加:您尝试在函数外部定义它 - 但为了使函数内部识别它,您必须全局化参数。)
当您 add_action 时,您需要定义 $arg 值:
Well, first off, in your my_function() function, you're not defining $arg. You're trying to echo something out that isn't there - so when it's returned, it's empty. So you need to define it. (edited to add: you're trying to define it outside the function - but to make the function inside recognize it, you have to globalize the argument.)
when you add_action, you need to define the $arg value:
您是否尝试将函数放在 add_action 之前?
Did you tried to put your function before add_action ?
使用这样的匿名函数:
有关详细信息,请参阅此答案。
Use an anonymous function like this:
See this answer for details.