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

JavaScript

How to add javascript file to wordpress?

I am trying to develop my own wordpress theme but stuck on a problem, it seems that the my js file is linked with my page but somehow its not doing anything. Someone Suggest me a way to make it work.

2 Answers

When you say it's not doing anything, that could be really one of three main things.

1) The JS file is being included in the source code correctly. You can use your dev tools to verify that pretty easily.

2) Your JS file has a error, or otherwise isn't configured correctly to do what you want it to do. This would be an error that would have nothing to do with WP, but just the JS file itself.

3) The order of your JS files are wrong. For instance, are you bringing in a JS file that relys on jQuery, before jQuery is included on the page? Source order is important.

Try tracking down those three possibilities first, and we can go from there.

function theme_enqueue_scripts() { 
     wp_register_script('script-name', get_template_directory_uri() . '/js/example.js', array(), '1.0.0', true );  
     wp_enqueue_script( 'script-name' ); 
} 
add_action( 'wp_enqueue_scripts', 'theme_enqueue_scripts' );

I already added the file using those wp tags but its not working, I added those codes in my functions.php file.