passing argument using add_action in wordpress!

穿精又带淫゛_ 提交于 2019-12-12 01:58:20

问题


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?


回答1:


Inside "my_function" (albeit it's yours :)), write line:

print_r(debug_backtrace());

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).




回答2:


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.)

function my_function($arg) {  
    if(!$arg) $arg = 'some value'; 
    echo "the var is:".$arg."<br>";
}

when you add_action, you need to define the $arg value:

add_action('admin_menu', 'my_function', 10, 'my value');



回答3:


Did you tried to put your function before add_action ?




回答4:


Use an anonymous function like this:

function my_function($arg) {
  echo "the var is: $arg<br>";
}
$arg = "HELP ME";
add_action('admin_menu', function() { global $arg; my_function($arg); }, 10);

See this answer for details.



来源:https://stackoverflow.com/questions/5800760/passing-argument-using-add-action-in-wordpress

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!