Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

164
Views
Combine Javascript files without erasing inline js

I have finally managed to combine all my WordPress Javascript from my theme and plugins into a single bundle using the function below:

function merge_all_scripts() {
    global $wp_scripts;

    $wp_scripts -> all_deps($wp_scripts -> queue);
    
    $merged_file_location = get_stylesheet_directory() . DIRECTORY_SEPARATOR . 'merged-script.js';
    $merged_script  = '';
    
    foreach( $wp_scripts->to_do as $handle) {
        $src = strtok($wp_scripts->registered[$handle]->src, '?');

        if (strpos($src, 'http') !== false) {
            $site_url = site_url();

            if (strpos($src, $site_url) !== false) $js_file_path = str_replace($site_url, '', $src);
            else $js_file_path = $src;

            $js_file_path = ltrim($js_file_path, '/');
        } else {            
            $js_file_path = ltrim($src, '/');
        }

        if  (file_exists($js_file_path)) {
            $localize = '';

            if (@key_exists('data', $wp_scripts->registered[$handle]->extra)) {
                $localize = $obj->extra['data'] . ';';
            }

            $merged_script .=  $localize . file_get_contents($js_file_path) . ';';
        }
    }

    file_put_contents ( $merged_file_location , $merged_script);
    wp_enqueue_script('merged-script',  get_stylesheet_directory_uri() . '/merged-script.js', array(), '1.0', false );

    foreach( $wp_scripts->to_do as $handle ) {
        wp_deregister_script($handle);
    }
}

add_action( 'wp_enqueue_scripts', 'merge_all_scripts', 99 );

Problem is it erases all inline woocommerce js defined in the "get_script_data" woocommerce function. I want it to include that aswell.

Otherwise content such as this will not get injected into the DOM, and therefore prevent the site from working properly:

var wc_add_to_cart_params = {"ajax_url":"\/wp-admin\/admin-ajax.php","wc_ajax_url":"\/?wc-ajax=%%endpoint%%","i18n_view_cart":"Se kurv","cart_url":"https:\/\/lawrence.dk\/bag\/","is_cart":"","cart_redirect_after_add":"no"};
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!