How many filter/action hooks are healthy?

As long as hooks don’t have anything hooked to them they are no-ops, that is do nearly nothing and have no considerable effect on runtime. It gets quite different when things are hooked and there are a lot of calls.

Since you talk about customizing strings the good example would be gettext hook in core. Every string that is localized passes through it.

So in theory this is a very flexible hook that allows to filter text nearly anywhere. In practice it can fire thousands of times and if you just hook into it unreservedly it will quickly slow down complex site to a halt.

You don’t cover your use case in sufficient detail to recommend specific implementation. In general you have multiple choices on how to organize this:

  • apply_filters( 'prefix_tooltip', $text ) is basic case, the filter would have to figure out does the text match exactly to determine context, thus fragile.
  • apply_filters( 'prefix_tooltip', $text, 'type/location' ) additional argument allows you to specify type of tooltip, which filter can target; so even if text changes, the type still identifies it.
  • apply_filters( 'prefix_tooltip_' . $type, $text ) dynamic hook name, which changes with variable value; this is very flexible for cases of many/generated types, the issue mostly is that dynamic hooks are harder to discover in code and are much worse at self-documenting;
  • apply_filters( 'prefix_tooltips', $texts_array ) single filter for complete set of tooltips used.

At a count of 6–8 entries there won’t really be meaningful performance difference between these.

What is important for you to learn here is what approaches there are and that you need to carefully pick the most appropriate one for every case, to have it be meaningful and convenient for yourself and downstream developers.

Leave a Comment

tech