I'm looking for a elegant way to register a ton of scripts I have sitting in a js directory on my server without having to sit and type them all out.

I found this question here but it is 3 years old, I'm basically after a similar solution and I would like to know if the following code I have adapted from the original question is suitable for the task?

Or alternatively, if there a better solution at all?

add_action( 'wp_loaded', 'theme_register_scripts' );
function theme_register_scripts() {

    $path = '/assets/js'; 
    $scripts = array_diff(scandir($path), array('.', '..')); 

    foreach ( $scripts as $k=>$v ) 
         wp_register_script( $k, get_template_directory_uri() . $v );

Thanks a bunch!

  • Are there no dependencies for these scripts? Jan 14, 2019 at 16:37
  • Just Jquery. basically they're components.
    – Beaniie
    Jan 14, 2019 at 16:38
  • You shouldn't need to type them all out, you can use tooling to generate the list, which would also be faster in production as it prevents the need to scan the directory
    – Tom J Nowell
    Jan 14, 2019 at 17:07
  • Sorry tooling? Could you point me in the direction of a manual?
    – Beaniie
    Jan 14, 2019 at 18:01


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.