The way the plugin system works in WordPress, plugin files are included in whatever order they happen to be in when the list of active plugins is saved to the database. There are plugins to control the load order of your plugins, but these are somewhat glorified hacks. There is certainly nothing wrong with them, but it is a bit bothersome to me that they are needed at all.
Whenever I write plugins, I make an effort put off the set up of everything, including adding any actions or filters, until the
plugins_loaded hook. This action happens immediately proceeding including the plugin files themselves, which in my mind makes it the perfect time to run set up.
Nothing else has run yet, but everybody’s been invited to the party.
If all plugins are written this way and one plugin needs to make a modification before another plugin sets up, or needs to load earlier than other plugins, or needs to make sure it loads after other plugins, it’s a simple matter of setting the correct priority on the
add_action() call that registers the setup function.
By this same token, I wait to do any theme setup until the
after_setup_theme hook. All theme files have been included, nothing else has run. This is somewhat less important since you’re not often running more than one theme, but in a child theme situation I still find it can be worthwhile.
Understanding when your code runs in relation to when other code runs can be very valuable. This little change in mindset when authoring code can help you keep your code just a bit more organized. It may also help another developer down the line when they need to get a bit of code running before yours does.
October 17, 2015 at 12:42 pm
Thanks, this is a very useful post 🙂