How to enqueue every script in a folder automatically?

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.

Leave a Comment