How to add your own JavaScript file to a WordPress Theme

Sometimes when you are developing a theme, you need to include some custom JavaScript or jQuery scripts, and they can become very lengthy when things start to get complicated. A great way to maintain order with all of your scripts is to load them into your theme as separate files. This also gives you the flexibility to load scripts when certain conditions are met, further extending the functionality and efficiency of the site. Today I’ll show you how to initialize and enqueue your own JavaScript files so they load at runtime.

functions.php

In your theme folder, open functions.php and add the following code:

This will declare a new function called, “add_custom_scripts.” In the function, we use wp_enqueue_script() to add our custom .js file to all of the pages when they are rendered. I use get_stylesheet_directory_uri() to grab the directory of the theme, and append the proper folder location of the file.

Leave a Reply

Your email address will not be published. Required fields are marked *