Using WordPress hooks is one of those topics that you hang around any Slack channel forum, email thread, Twitter conversation, or whatever and you’ll find that understanding them and using them correctly is key to working with the application.

Using WordPress Hooks

But if there’s one thing that I get obsessive about, is using the right hook (as opposed to the left hook 🙃).

Sure, that reads weird, but look at it this way:

  • each hook offers a variety of parts of the application available at a given time,
  • and each hook is given a specific name.

So it would stand to reason that we try to hook our functions into the hook that’s most closely aligned and appropriately named for our particular requirement, right?

Using WordPress Hooks (But Differently)

For example, let’s say that I’m working on a plugin that’s obviously going to be using WordPress hooks and I’ve got a file that kick-starts the whole process (namely, a bootstrap file). I typically attach this to plugins_loaded and then I let the plugin do its thing.

This satisfies both requirements above:

  • the plugin is attached to WordPress at a time where the necessary resources are available,
  • the plugin is attached to a hook with a name that makes sense.

What happens, though, whenever we’re working on a plugin that needs resources later in the application, earlier in the application, or simply need something that isn’t available when plugins_loaded fires.

What then?

Personally, I get a bit obsessive about how I set up my plugins so having to using WordPress hooks differently than I’d like for my initial function irritates me. I feel like it creates less-clean code in that it doesn’t read as well.

What do you mean, you’re starting this function with wp_loaded? Wouldn’t this always work with wp_loaded?

Maybe that’s a bad example but you get my point.

And sure, there are strategies initialize components at different points in the WordPress lifecycle and then have them work altogether, but that’s more advanced than the purpose of this post.

What’s the Point of This?

All I’m trying to say is that if you’re someone who tries to align bootstrapping their plugin with a hook that’s at the best possibly time in WordPress’ execution and creates the cleanest code, accept that sometimes using different WordPress hooks are a nature of working with the application.

Sometimes, certain features or components just aren’t ready for when your plugin needs them. So you’re left with either trying to execute a plugin prematurely, or using a hook that may lack a name of clarity but has the resources you need.

And the worst case scenario? You document what you’re doing in the code comments.