What's the best way to add multiple JavaScript files to a WordPress theme?

Hey everyone! I’m new to WordPress and PHP, and I’m struggling to add more than one JavaScript file to my theme. I’ve got two files I want to include:

  1. my-scripts.js
  2. dropdown-menu.js

I’m using this code in my functions.php file:

function load_theme_scripts() {
    wp_enqueue_script('main-script', get_template_directory_uri() . '/js/main-script.js', array('jquery'));
}
add_action('wp_enqueue_scripts', 'load_theme_scripts');

This works for one file, but I’m not sure how to add the second one. Can anyone help me figure out how to include both JS files in my WordPress theme? Thanks in advance!

I faced a similar challenge when I was starting out with WordPress theme development. The good news is, it’s pretty straightforward to add multiple JavaScript files. You’re on the right track with wp_enqueue_script(). Here’s how I’d modify your existing code to include both files:

function load_theme_scripts() {
wp_enqueue_script(‘main-script’, get_template_directory_uri() + ‘/js/my-scripts.js’, array(‘jquery’), null, true);
wp_enqueue_script(‘dropdown-menu’, get_template_directory_uri() + ‘/js/dropdown-menu.js’, array(‘jquery’), null, true);
}
add_action(‘wp_enqueue_scripts’, ‘load_theme_scripts’);

This approach allows you to enqueue multiple scripts independently. The ‘true’ at the end loads the scripts in the footer, which can improve page load times. Just make sure your file paths are correct. Also, if your dropdown-menu.js depends on my-scripts.js, you’d need to adjust the dependencies accordingly.

hey there! i’ve been there too. here’s a quick trick:

function load_theme_scripts() {
wp_enqueue_script(‘my-scripts’, get_template_directory_uri() . ‘/js/my-scripts.js’, array(‘jquery’));
wp_enqueue_script(‘dropdown-menu’, get_template_directory_uri() . ‘/js/dropdown-menu.js’, array(‘jquery’));
}
add_action(‘wp_enqueue_scripts’, ‘load_theme_scripts’);

just add another wp_enqueue_script() line for each file. easy peasy!

Adding multiple JavaScript files to a WordPress theme is quite straightforward. You’re already using wp_enqueue_script() correctly, which is the recommended method. To include both files, simply call wp_enqueue_script() twice within your load_theme_scripts() function. Here’s how you can modify your existing code:

function load_theme_scripts() {
wp_enqueue_script(‘my-scripts’, get_template_directory_uri() + ‘/js/my-scripts.js’, array(‘jquery’), null, true);
wp_enqueue_script(‘dropdown-menu’, get_template_directory_uri() + ‘/js/dropdown-menu.js’, array(‘jquery’), null, true);
}
add_action(‘wp_enqueue_scripts’, ‘load_theme_scripts’);

This approach ensures both scripts are loaded properly. The ‘true’ parameter at the end places the scripts in the footer, which can improve page load performance. Remember to adjust the file paths if needed, and consider any dependencies between your scripts.