Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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);
share|improve this question
1  
Where have you seen this!? –  TheDeadMedic Mar 18 at 15:27

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

share|improve this answer

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.

share|improve this answer

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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