How to change order inside foreach using wp_enqueue_script?


I have a created a for each loop to load all the script files from my build folder dynamically in the footer with for development and production mode. This way I don’t need to manually replace the script files.

But I have a problem, I don’t know how to change the order of the files to a specific order.

It should be: Runtime, Vendors, Main.

This is my PHP code:

// First check if "JS" folder exist to prevent errors.
if(is_dir(THEME_DIR_ASSETS . '/js')) {
    // Enqueue all scripts.
    function nm_enqueue_scripts() {
    $directoryJS = new DirectoryIterator(THEME_DIR_ASSETS . '/js');

        wp_enqueue_script('jquery', '', array(), null, false);

        foreach ($directoryJS as $file) {
            if (pathinfo($file, PATHINFO_EXTENSION) === 'js') {
            $fullName = basename($file);
            $name = substr(basename($fullName), 0, strpos(basename($fullName), '.'));

            wp_enqueue_script($name, THEME_DIR_JS . '/' . $fullName, $name, null, true);
    add_action('wp_enqueue_scripts', 'nm_enqueue_scripts');

How can I do this?

, , Galanthus 4 years 2020-02-20T08:41:48-05:00 0 Answers 68 views 0

Leave an answer