WordPress中跨插件的自定义钩子 [英] Custom hooks in WordPress across plugins
问题描述
我正在尝试在一个Wordpress插件中创建一个可供其他插件使用的钩子.首先,这有可能吗?我还发送了一些附加的参数,因此这可能是两个问题,因为我一直难以找到有关如何执行此操作的明确信息.
I'm trying to create a hook in one Wordpress plugin that could be used by other plugins. First off, is this even possible? I'm also sending some additional args so this may be 2 questions in one since I've been having trouble finding definitive information on how to do this.
这是我到目前为止尝试过的:
Here is what I've tried so far:
在创建钩子的插件(称为插件1)中,我添加了:
In the plugin that is creating the hook (call it Plugin 1) I added:
do_action('plugin1_hook', $customArg1, $customArg2, $customArg3);
在我想要钩子开火的那一点上.然后,在另一个插件(插件2)中,我添加了:
at the point that I want the hook to fire. Then, in a different plugin (Plugin 2), I added:
add_action('plugin1_hook', 'my_function');
和
function my_function($customArg1, $customArg2, $customArg3) { //my code }
但是,这似乎并未触发该功能. 我的参考是Wordpress钩子comment_post,它由Wordpress定义为:
This does not seem to be firing the function, however. My refence for this has been the Wordpress hook comment_post, which is defined by Wordpress as:
do_action('comment_post', $comment_ID, $commentdata['comment_approved']);
我正在使用:
add_action('comment_post', 'my_comment');
function my_comment($comment_id) { //my code }
上面的代码段运行正常.
The above snippet is functioning properly.
推荐答案
我认为我将其发布为答案,因为这样可以更清楚地解释:)
I thought I'd post this as an answer as it's a little clearer to explain :)
当您钩住函数但未指定参数数量时,WordPress将始终传回一个参数.
When you hook a function, but do not specify the number of arguments, WordPress will always pass back one argument.
类似这样的东西,您不会出错;
You won't get errors for something like this;
function do_my_hook($arg1, $arg2 = '', $arg3 = '') {}
add_action('my_hook', 'do_my_hook');
但是您会想要这样的东西;
But you will for something like this;
function do_my_hook($arg1, $arg2, $arg3) {}
add_action('my_hook', 'do_my_hook');
WordPress正在尝试调用do_my_hook()
,但是它只传递了一个参数.第一个示例使用 PHP默认函数参数,因此您可以在不传递所有可用参数的情况下调用函数,但不会出错.
WordPress is trying to call do_my_hook()
, but it's only passing back one argument. The first example uses PHP default function arguments, so that you can call a function without passing all available arguments, but without error.
第二个示例将触发缺少参数"的PHP错误,因为所有三个参数都是必需的.
The second example will trigger a 'missing argument(s)' PHP error, as all three arguments are required.
解决方法?
add_action('my_hook', 'do_my_hook', 10, 3);
定义函数采用多少个参数的想法是避免出现此类错误(尽管从技术上讲,使用默认参数很容易避免这些错误!).
The idea behind defining how many arguments your function takes is to avoid errors like these (though technically they are as easily avoided using default arguments!).
这篇关于WordPress中跨插件的自定义钩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!