我认为你不应该使用$GLOBALS
完全add_filter
不应该用你现在使用的方式。
所以有apply_filter
在wordpress中返回filtered 值,以便
$my_variable = apply_filter(\'my_filter_tag\', \'default_value\', $arg1);
在上述代码中
\'default_value\'
可以是任何东西
$my_variable
将hold 价值观\'default_value\'
如果没有人打电话add_filter(\'my_filter_tag\', \'my_function_name\', 10, 2)
当有人打电话时add_filter(\'my_filter_tag\', \'my_function_name\', 10, 2)
这意味着$my_variable = my_function_name(\'default_value\', $arg1);
以下是$my_variable
将等于my_function_name
因为我们注册了my_function_name
每次调用$my_variable
正在设置。
要达到帖子中描述的预期效果,您可以执行以下操作:
# This will set the value of $GLOBALS[\'x\'] = 1 by default if there are no hooks called.
# $arg1 is optional but since you specified the value 2 when registering the filter I\'ve added it to the example to explain it
$GLOBALS[\'x\'] = apply_filter(\'filter_hook\', 1, $arg1);
function my_function($x, $y) {
# Here this function required two parameters
# This function is being called by the filter_hook
# So the value of $x will be equal to 1 ( Which is the default value)
# $y will be $arg1
return 2; # Notice that we\'re returning the value rather than setting it.
}
# Here the value 10 means priority and the value 2 means that the function
#`my_function` will be given two arguments when it is called, the first argument
# for the called function will always be the \'default_value\'
add_filter( \'filter_hook\', \'my_function\', 10, 2 );
add_action( \'action_hook\', \'my_function2\', 10, 2 );
function my_function2() {
echo $GLOBALS[\'x\'];
}