简体   繁体   English

如何在wordpress插件中绑定到动作钩子的函数之间传递我自己的变量

[英]How can I pass my own variables between functions tied to action hooks in wordpress plugins

I am writing a Wordpress plugin in PHP and I want to be able to use a variable that is not provided in the action hook (of other separate) plugin. 我正在用PHP编写Wordpress插件,我希望能够使用动作钩子(其他单独的)插件中没有提供的变量。 I want to pass a variable from one hook to another. 我想将一个变量从一个钩子传递给另一个钩子。

These functions are in my functions.php file (not the theme functions file). 这些函数在我的functions.php文件中(不是主题函数文件)。

I cannot nest the action hooks because they happen at different times, specifically, the one with the variable happens after the one with where I want it. 我无法嵌套动作挂钩,因为它们发生在不同的时间,具体而言,变量发生在我想要它的地方之后。

I don't think I can use a closure because the variable is inside another hook. 我不认为我可以使用闭包,因为变量在另一个钩子里面。

I can't use a class because if I set the class in action 1 then it's not in scope in action 2 and I need to make a new one. 我不能使用类,因为如果我在操作1中设置类,那么它不在操作2的范围内,我需要创建一个新类。

I could use a global or access the DB but I feel like there should be a better way than either of those. 我可以使用全局或访问数据库但我觉得应该有比其中任何一种更好的方法。

action 1 - my plugin 动作1 - 我的插件

function foo($level){
  do stuff
}
add_action('change-membership', 'foo');

action 2 - my plugin 动作2 - 我的插件

function bar(){
  if($level==0){
    do stuff
  }
}
add_action('put-in-checkout-text', 'bar');

Other devs plugin 其他开发者插件

do_action('change_membership', $level);

// a little later
do_action('put_in_checkout_text');

$levels exists at the time I want it - but there is no action hook at that point to grab it. $ level存在于我想要的时候 - 但是在那一点上没有动作钩子来抓住它。

What I understand is you have something like this: 我明白你有这样的事情:

// Plugin 2, the plugin you are writing.
do_action('put_in_checkout'); // --> bar()

// Plugin 1, another author's plugin
$level = "definition of level";
do_action('change_membership', $level); // --> foo($level)

You say you need to access to $level before the change_membership action happens, so $level may not be defined at that time. 您说您需要在change_membership操作发生之前访问$level ,因此当时可能无法定义$level Even if it was, it may be in a scope not reachable from put_in_checkout handler functions. 即使它是,它可能在put_in_checkout处理函数无法访问的范围内。 Just in case, check if plugin 2 instanciates a global variable where you have access to the value of $level . 以防万一,检查插件2是否实例化了一个全局变量,您可以访问$level的值。 Otherwise, you need to take it from the database (if it is stored there) or generate it somehow. 否则,您需要从数据库中获取它(如果它存储在那里)或以某种方式生成它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM