Most elegant way to enqueue scripts in function.php with foreach loop

You need to enqueue the scripts as well, not only register them. You can, however, just simply enqueue a script without registering it if you are not going to enqueue it conditionally.

I would try something like this: (Untested and requires PHP5.4+)

add_action( 'wp_enqueue_scripts', enqueue_scripts, 11 );
function enqueue_scripts()
{
    /**
     * Build an array of scripts to enqueue
     * key = script handle
     * value = path to the script without the get_template_directory_uri()
     */
    $scripts = [
        'script-1' => '/script.1.js',
        'script-2' => '/js/script.2.js',
        'script-3' => '/subfolder/script.3.js',
    ];
    foreach ( $scripts as $k=>$v )
        wp_enqueue_script( $k, get_template_directory_uri() . $v );
}

EDIT

As explanation to a comment to the answer, the add_action() call can go anywhere, it does not even needto be in the same template. It can go above or below the function declaration. I prefer to add the add_action() call above the function as this just makes more sense when you think about closures. When using closures, the code above will look something like this:

add_action( 'wp_enqueue_scripts', function ()
{
    /**
     * Build an array of scripts to enqueue
     * key = script handle
     * value = path to the script without the get_template_directory_uri()
     */
    $scripts = [
        'script-1' => '/script.1.js',
        'script-2' => '/js/script.2.js',
        'script-3' => '/subfolder/script.3.js',
    ];
    foreach ( $scripts as $k=>$v )
        wp_enqueue_script( $k, get_template_directory_uri() . $v );
}, 11 );

So you see, it just makes more sense 🙂

Leave a Comment