Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

WordPress WordPress Theme Development WordPress Header and Footer Templates Porting existing headers and footers into WordPress

Why is wp_enqueue_scripts used instead of wp_head?

Hey,

So I just have a quick question. Inside my functions.php file, why does it say...

add_action('wp_enqueue_scripts', 'wpt_theme_styles');

instead of

add_action('wp_head', 'wpt_theme_styles');

It just seems to me that the second statement would make more sense. If the wp_head() is seen in the header.php page, then it would trigger the function wpt_theme_styles, which would load all the style pages into the header.

Then, if we add something like

add_action('wp_footer', 'wpt_theme_js');

then, when wp_footer() is seen, it would trigger the wpt_theme_js function, which would load javascript files into the footer.

Why is it not done this way?

3 Answers

Andrew Shook
Andrew Shook
31,709 Points

The reason you use wp_enqueue_scripts instead of wp_head and wp_footer is mostly for brevity. With wp_enqueue_scripts, you can add JS and CSS in one function instead of two ( one for the js and css in the header and one for the footer). Then inside the wp_enqueue_scripts you can tell it to place the JS in the footer or header.

  • Then inside the wp_enqueue_scripts you can tell it to place the JS in the footer or header.

How do you do that?

Andrew Shook
Andrew Shook
31,709 Points

You use the wp_enqueue_script function. If you look at the documentation here you will see that the last parameter you pass the function is a boolean that tells WP to add the script to the end of the page or the beginning. If you put true it will add it JS right before the closing body tag. If you put false or leave that parameter out it will add the script in the head tag.

Ok cool...but what about when you use the wp_enqueue_styles function? How does it know to go to the wp_head()?

Andrew Shook
Andrew Shook
31,709 Points

It knows to print the stylesheet links when wp_head is called because that is it's built in functionality.

Ok, that's answers my question. Thanks Andrew!