I have a whole entire js
folder of scripts and it would be tedious to have to load them all with wp_enqueue_script()
one by one.
Is there a way I can just insert the directory they are all in and it do it for me?
I have a whole entire js
folder of scripts and it would be tedious to have to load them all with wp_enqueue_script()
one by one.
Is there a way I can just insert the directory they are all in and it do it for me?
There’s nothing wrong with enqueuing many files by using wp_enqueue_script
. If you are referring to it as frustrating, then there is a simple solution for this.
PHP offers a function that can list files and directories. By using glob
you can list every .js
file in your directory, and then enqueue them by a loop.
function enqueue_my_scripts(){
foreach( glob( get_template_directory(). '/path/*.js' ) as $file ) {
// $file contains the name and extension of the file
wp_enqueue_script( $file, get_template_directory_uri().'/path/'.$file);
}
}
add_action('wp_enqueue_scripts', 'enqueue_my_scripts');
A side not is that glob
uses relative path, but wp_enqueue_script
uses URLs. That is why I used different functions to get the folder’s path and URI.