1

I see a lot of plugins using this approach to add a new hook, e.g.

add_action('init', function() {
   add_action('SOME_LATER_HOOK', xxx);
   add_filter('SOME_LATER_FILTER', yyy);
});

Why they don't just add the hook directly? I see there are no benefit anyway, e.g. performance

Why not just

add_action('SOME_LATER_HOOK', xxx);
1
  • 1
    Where have you seen this!? Mar 18, 2014 at 15:27

3 Answers 3

3

Sometimes you want to run some code before deciding to add an action, or a filter. This may involve checking the user's permissions, checking the type of page request, checking whether another plugin is active etc.

Some of those checks may not be possible until some way through WordPress' execution - so it's reasonably common to do that work in an init hook, rather than on plugin inclusion.

Doing everything like this means that your "initialisation" is all in one place, even if some of your actions don't require it.

2

If necessary it is easier to remove one function from init than two (or maybe fifty) from all over.

It is commonly recommended to not run anything before init hook in general, so that's typical starting point even when it isn't forced by required technical implications.

0

Adding hooks on hooks seems to me pretty profligate-- a waste of resources. If you do that, you have two or more calls to add_user_func_array(), where you would otherwise only have one and that is not to mention the other work that is done processing before that point.

The exceptions are:

  • When you need to use a function and need to make sure that that function is available. This is sometimes necessary with mu-plugins, which load fairly early, as done here. A MU-Plugin won't be able to use plugin code unless hooked in after plugins load, for example.
  • Or when some hook provided information not easily available in the hook that does the work, as in this answer.

It is also possible to "chain" hooks to provide a bit of flexibility to some special purpose code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.