开发者

passing argument using add_action in wordpress!

开发者 https://www.devze.com 2023-03-01 03:34 出处:网络
I have a very strange problem in my wordpress development, in fucntions.php I have the following code //mytheme/functions.php

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 ar开发者_运维百科gument "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?


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


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');


Did you tried to put your function before add_action ?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消