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.

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?

share|improve this question
add comment

2 Answers

up vote 3 down vote accepted

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.

share|improve this answer
    
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 '12 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 –  Mario Peshev Nov 11 '12 at 20:25
add comment

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

share|improve this answer
    
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 '12 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. –  Mario Peshev Nov 11 '12 at 20:31
add comment

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.