1

Related to this question (Use wp init hook to call other hooks?) but not the same.

Sometimes, I found that the hook will failed to run when I place inside the init hook, e.g.

Not Work:

add_action('init','my_init');
function my_init() {
    add_filter('locale', ...
}

Work:

add_action('init','my_init');
add_filter('locale', ...

Of course some hooks/filters will just work okay inside the init hook, but definitely not all of them.

So it seems to me that it is a bad practice to chain actions/filters together?

2 Answers 2

4

The locale hook happens long before init. To see when which hook, variable, constant, function, class or file is available install my plugin T5 WP Load Order.

You get a looong file with a very detailed log. Search for Hook: locale, then for Hook: init. You will see that you need plugins_loaded as parent action if you want to chain hooks.

Is it a good practice? It depends. If you need the second callback only when the first was running successful, then yes. If both callbacks should run independently of each other, then no.
Chaining should reflect the logic of your program.

2
  • Thanks, will definitely check out your plugin to have a look. The reason I ask is the init hook of your plugin must success anyway if the plugin is activated, so chaining inside the init just delay the execution and caused the troublesome in dependency.
    – Yoga
    Nov 11, 2012 at 18:44
  • That plugin looks great, thanks for sharing it. Another awesome one is the WordPress Hook Sniffer - wordpress.org/extend/plugins/wordpress-hook-sniffer Nov 11, 2012 at 20:25
2

Attaching to a hook inside of a callback of another hook is not a bad practice, contrary, sometimes it's mandatory. The problem is that you should be aware of the sequence of actions and filters, as you could try to invoke an action while you're executing something else after the first action (so your second hook is already executed and it's too late for newly attached events).

2
  • Hi, as the dependency stuff of action/filter is fragile and error prone, I am thinking - always register earlier and let your callback to decide if it should be executed seems to be a better approach
    – Yoga
    Nov 11, 2012 at 18:47
  • Quite true, though it's not always possible to register at earlier point due to the fact that data-sensitive variables are used (like post, or whatever), also you could mess up the future flow if your logic is branched. Nov 11, 2012 at 20:31

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.