Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

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.