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 trialDrew Gillett
156 PointsAdding 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
Drew Gillett
156 PointsIt 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
9,052 PointsThe 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
Drew Gillett
156 PointsThank 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
9,052 PointsOops! 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.