3

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?

1
  • 2
    How many scripts are you talking about? How long? The best solution from both a convenience as well as performance perspective might very well turn out to be combining them all into one or two js files, and then enqueueing them.
    – CK MacLeod
    Aug 14, 2017 at 22:28

2 Answers 2

9

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.

1
  • 2
    Unless this is a child theme, then template should be stylesheet.
    – rudtek
    Aug 15, 2017 at 1:24
1

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);
}
1
  • 1
    I think basename() would be easier to read, and maybe even faster. :)
    – fuxia
    Dec 30, 2017 at 17:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.