0

Is it possible to create a new action hook like do_action('my-hook-name'); inside a call to add_action();?

I'm aware this code doesn't work, but I was thinking something along the lines of... add_action('init', do_action('my-hook-name'));

or

Is the only way to actually add a callback function to init, then inside my callback function create my hook?

add_action('init', 'my_callback');
function my_callback(){
    do_action('my-hook-name');
}
  • Yes, it's possible. What's the use-case, though? Why not just fire on the existing action you hook into? – Chip Bennett Nov 13 '13 at 18:53
  • Creating a plugin which hooks into theme hooks. Looking to provide plugin hooks to the theme hooks. It's not a big deal to actually create a callback, just thought it would be nice to have shorter code. – Michael Ecklund Nov 13 '13 at 18:55
  • Out of curiosity, does it work for you? I mean, the second parameter is supposed to be a callback (just asking, for I get an error) – Ivan Hanák Nov 13 '13 at 19:07
  • 1
    In such a case, anonymous function should do the magic add_action('init', (function(){do_action('i_am_a_hook');})); – Ivan Hanák Nov 13 '13 at 19:35
  • 1
    And anonymous functions in hook calls are not user- or child-theme friendly. – Chip Bennett Nov 13 '13 at 19:49
0

Creating an answer based upon responses via comments on original question of: Is it possible to create an action hook using do_action() within add_action()?

Yes it is possible to create an action hook using do_action() on a call to add_action().

For clarification, the following code does NOT work:

add_action('init', do_action('my-hook-name'));

As stated by @IvanHanák in the comments to the original question asked; It is possible to create an action hook using do_action() on a call to add_action() by using anonymous functions.

An example of creating an action hook using do_action() on a call to add_action() using anonymous functions:

add_action('some-existing-hook-name', function(){do_action('my-new-hook-name');});

However, it should be noted that using anonymous functions can make it difficult to debug or remove hooks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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