Hey everyone! I’m new to WordPress and PHP, and I’m stuck trying to add two JavaScript files to my theme. I’ve got one working, but I can’t figure out how to add the second one. Here’s what I’m trying to do:
- Add
js/main-scripts.js
- Add
js/dropdown-menu.js
I’m using this code right now:
function load_theme_scripts() {
wp_enqueue_script('main-scripts', get_template_directory_uri() . '/js/main-scripts.js', array('jquery'));
}
add_action('wp_enqueue_scripts', 'load_theme_scripts');
This works for one file, but how do I add the second one? Any help would be awesome. Thanks!
I’ve been through this exact situation when I was starting out with WordPress themes. Here’s what I learned:
You’re on the right track with wp_enqueue_script(). The beauty of this function is that you can use it multiple times within the same load_theme_scripts() function. No need for separate functions for each script.
In your case, just add another line for your dropdown menu script:
function load_theme_scripts() {
wp_enqueue_script(‘main-scripts’, get_template_directory_uri() . ‘/js/main-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’);
This method has always worked well for me. Just make sure your file paths are correct. If you run into any issues, double-check that first. Also, remember that the order of enqueuing can matter if one script depends on another. Good luck with your theme!
Adding multiple JavaScript files to your WordPress theme is straightforward. You can enqueue both files within the same function. Here’s how you can modify your existing code:
function load_theme_scripts() {
wp_enqueue_script('main-scripts', get_template_directory_uri() . '/js/main-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');
This approach allows you to add as many scripts as needed. Each wp_enqueue_script() call registers a new script. Make sure the file paths are correct relative to your theme directory. Also, if your dropdown menu script depends on main-scripts.js, you can specify that dependency in the third parameter of wp_enqueue_script() for the dropdown script.
yo, adding multiple js files is easy peasy! just stack em up in ur function like this:
function load_theme_scripts() {
wp_enqueue_script(‘main-scripts’, get_template_directory_uri() . ‘/js/main-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’);
thats it! make sure ur file paths r right tho. good luck!