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


Adding javascript to Wordpress Theme

I'm in the process of converting an HTML site to a Wordpress site, and am still going through the WP vids but haven't yet figured out where the javascript files are made accessible by the various pages throughout the theme. Can you give me a hand with this?

3 Answers

It appears this was misfiled, and the site is denying me the right to edit it. It's more a Wordpress query than a js one. Apologies!

Christopher Hall
Christopher Hall
9,052 Points

The proper way to add external Javascript files to a Wordpress theme is to use the wp_enqueue_script function in your theme's functions.php file. The files themselves can be within a subfolder in your theme.

Edit: functions.js updated to intended answer of functions.php

Thank you. The page however seems to primarily mention the use of PHP and not JS as the means of doing it, and inserting it in the header rather than in the functions.js file. Wouldn't that then correspond to the functions.php file?

Could you please elaborate? Thanks!

Christopher Hall
Christopher Hall
9,052 Points

Oops! Yes, I meant the functions.php file for the Wordpress theme, not functions.js. Sorry, I answered it quickly on a break at work.

You can just add the script tags to your theme's header.php file, but that's not a good practice since it could cause conflicts (different versions of jQuery trying to be loaded, etc) with Wordpress scripts or plugin scripts. The benefit of defining a hook in functions.php and using wp_enqueue_script is that it only loads the script if it has not already been loaded, and if you specify dependencies it will order the script(s) to be loaded after the one it depends on. You can also have it put the script in the footer instead of the header for performance reasons.