Should I use the function add_filter
In my plugin’s init
action hook or just the in the main plugin script?
Since sometimes I found people is using filter all over the place and if I put in the init
hook, it would be too late for some case.
Are there any general advice on the precedence of action
& filter
hook so we can have a more consistent code style?
add_filter()
andadd_action()
are available before any plugin is loaded. So you can use both in the first line of your plugin or theme.For readability I recommend to group action and filter registrations at the very top of your main file:
functions.php
There are exceptions for that rule:
shutdown
only when the first filter forwp_nav_menu_objects
has been called. So the second callback cannot be registered at the same time as the first one.OOP style. Sometimes you have to set up class members before you can register the callbacks. Using a very similar example â¦
⦠we see the instantiation of the class can be stopped by another plugin, and a child class could register more or different filters and actions.
In addition to grouping you can go a step further and offer a custom action to make customizations for other developers easier.
Here is an example from a theme I am working on:
The last line is important: A child theme or a plugin can hook into the action
t5_theme_hooks_registered
now and unregister any previous hook. That will save struggling with priorities, and I am free to change my callback priorities any time.But do not rely on source code order alone. Document the hooks you are using in your doc block. I am using a custom tag
wp-hook
for that. Here is an example with chained hooks from the same theme:You donât have to scroll up to see where these functions are called, one look at the doc block is enough. This requires some efforts, because you have to keep both in sync, the registration and the comment, but in the long run it saves valuable time.