I am using WordPress 3.1.4 by now. I am confused with where (which hook) do I use:
- to register and/or enqueue
- scripts and styles
- on front- and back-ends?
Questions:
- Which are right hooks to use?
- All front end register/enqueue scripts/styles in
init
? - Why is there no
admin_print_styles-{xxx}
?
Why registering and queuing properly matters
it should be in time – earlier than script/style is up for being output to page, otherwise it is too late;
it should be conditional – otherwise you are loading stuff where you don’t need it and cause performance and functionality issues, for this you need WP environment loaded to late stage.
The three stages of the process
register – this explains WP details about script/style and makes it store that info;
enqueue – (often lumped together with register in one
wp_enqueue_*()
call) – this tells WP to add scripts/style to the queue, according to its settings (dependencies, header/footer loading).print – this happens when WP processes queue, tries to load something specific for itself or when you explicitly do it with
wp_print_*()
function.Front-end structure of functions and hooks
wp_head()
wp_head
(1)
wp_enqueue_scripts()
wp_enqueue_scripts
« this is what you need(8)
wp_print_styles()
(9)
wp_print_head_scripts()
wp_footer()
wp_footer
wp_print_footer_scripts()
It goes much deeper, but this is simple and good enough for important points:
wp_enqueue_scripts
is most appropriate hook for registering and queuing scripts and styles on front end and it is there specifically for that;init
has nothing to do with this, it will work, but – past Codex recommendation to use only it was incorrect;you can get away with queuing scripts (not styles) for footer at any point before
wp_print_footer_scripts()
call;wp_print_*
hooks are NOT appropriate for register/queue, they are points in code when output is already happening. They are appropriate for manual/custom script/style output.What about admin?
Well, the functionality there is even more complex, elaborate and nested.
for starters just use
admin_enqueue_scripts
hook (it gets passed$hook_suffix
global for conditional stuff) for everything, it will do nicely for most cases;when you need something complex – look through
admin-header.php
and dig from there for appropriate hooks.What about login?
There’s a specific hook named
login_enqueue_scripts
.