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.
On WordPress 4.9 using the relative path (get_template_directory) returned $file as the complete path, which is unusable on a shared server. I found I had to use the substr function to return just the file name, and then build the URI from that.
foreach( glob( get_template_directory(). '/path/*.js' ) as $file ) {
$filename = substr($file, strrpos($file, '/') + 1);
wp_enqueue_script( $filename, get_template_directory_uri().'/path/'.$filename);
}
basename()
would be easier to read, and maybe even faster. :)