Failed to invoke other hook from the init hook

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.

Read More

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?

Related posts

Leave a Reply

2 comments

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