Why do we need to enqueue styles on a hook, why not just enqueue them straight in like this?

wp_enqueue_style( $handle, $src);

the codex page gives an example of using a hook but doesn't explain why (or if) it's important.


There is code that needs to run, thing that need to be setup, before you enqueue. If you enqueue too early those prerequisites will not be filled and you will see ...

Notice: wp_enqueue_style was called incorrectly. Scripts and styles should not be registered or enqueued until the wp_enqueue_scripts, admin_enqueue_scripts, or init hooks. Please see Debugging in WordPress for more information.

... if you have debugging enabled.

The register/enqueue system is complex-- look at the files named class.wp-scripts.php, class.wp-styles.php, and class.wp-dependencies.php. It does not just echo content to the page header. The code tries to handle dependency loading and prevent the loading of the same file more than once. For that to work things have to be registered and enqueued at the right time in the load process, hence loading on hooks.

That is not to say that enqueueing a file immediately won't work. It might. It depends on where you try to enqueue. As per the message, you need to enqueue after wp_enqueue_scripts, admin_enqueue_scripts, or init. Even so, I believe that some things don't work if you enqueue after wp_enqueue_scripts. For example, you can't get a file to load in the header if you try to enqueue it late in the page load. So be careful with it and just try to avoid hook-less enqueueing.

  • Am I right in saying then that the codex page is misleading because it gives the impression that hooking is optional, but from what you say it seems like it's not. – byronyasgur May 6 '13 at 20:38
  • Mostly it is not optional. The Codex page has a warning about enqueueing outside of hooks. – s_ha_dum May 6 '13 at 20:49
  • ... so it's not mandatory? I'm confused I thought you meant it was mandatory ... do you not think the codex implies it's optional? – byronyasgur May 6 '13 at 20:57
  • The answer is a wee bit more complicated than "mandatory" or "not mandatory". I said that there is code that needs to run before you enqueue. That is the same thing implied by the notice. Most of the time that is going to mean enqueueing on a hook. The rest of the time, be careful. – s_ha_dum May 6 '13 at 21:33
  • Well maybe mandatory is the wrong word ... but it's not really optional is it? You seem to be implying the codex is correct, which is confusing me, because surely it shouldn't be implying that you can leave out the hook ... I mean if as you say you get a debug error. – byronyasgur May 6 '13 at 21:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.