Custom hooks in WordPress across plugins

一个人想着一个人 提交于 2019-12-05 03:53:19

I thought I'd post this as an answer as it's a little clearer to explain :)

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

The second example will trigger a 'missing argument(s)' PHP error, as all three arguments are required.

The fix?

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

My guess is the second plugin is loading after the first one, so the hook has already fired by the time you add an action to it. You might try this for the first plugin:

function my_custom_hook_insertion($arg1, $arg2, $arg3){
  do_action('plugin1_hook', $arg1, $arg2, $arg3);
}
add_action('plugins_loaded', 'my_custom_hook_insertion');

That will wait until all plugins are loaded before firing the hook.

Changing my add_action to this fixed the problem:

add_action('plugin1_hook', 'my_function', 10, 3);

The 10 represents the priority, and the 3 represents the number of args that the function will take. I'm not exactly sure how the matching works, since the default is 1, and I use plenty of hooks without specifying 0 args and I've used hooks that pass more than 1 arg but only used 1 arg in my function signature. Source: WordPress Codex: Function Reference/add action

It is working though, so cross plugin hooks are possible.

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