Is it possible to filter the wp_footer() scripts, read the content, and insert them inline?

I need to intercept the scripts that are added in the footer and head through the wp_footer() and wp_head() functions, something like add_filter('wp_footer', my_function) and then in my_function, I would check the name of the registered script and then perform an action, in that case would read the contents of the script.js file and insert it inline, something like this:

Before intercept (this is showing on footer or head):

script type="text/javascript" src="mywp/wp-content/plugins/plugin-name/script.js"

After intercept, I want to show inline script like this:

script
    // this is content of plugin script.js or other intercepted scripts...
    var content_is_here = ....
    function() {
        // content inline etc
    ...
    }
/script

Is possible do this? On intercepting, i need name of script and path to read the content and insert inline, this I know how to do, but I don't have idea of how to intercept scripts...

If is possible to intercept CSS files too would be very good!

Thanks in advance!

Topic request-filter wp-query php plugins Wordpress javascript

Category Web


For scripts you can use the script_loader_tag filter, which is run right before the script tag is output. It filters the HTML <script> tag, but it also passes the handle and URL that you can use to extract the contents and replace the script tag with a version that has the script inline:

function wpse_292955_inline_script( $script, $handle, $src ) {
    if ( $handle === 'script-handle' ) {
        $script = sprintf( '<script type="text/javascript">%s</script>', file_get_contents( $src ) );
    }

    return $script;
}
add_filter( 'script_loader_tag', 'wpse_292955_inline_script', 10, 3 );

There's also style_loader_tag for styles:

function wpse_292955_inline_style( $html, $handle, $href, $media ) {
    if ( $handle === 'style-handle' ) {
        $html = sprintf( 
            '<style type="text/css" media="%s">%s</style>', 
            esc_attr( $media ),
            file_get_contents( $href )
        );
    }

    return $html;
}
add_filter( 'style_loader_tag', 'wpse_292955_inline_style', 10, 4 );

Note that because scripts and styles are registered with a URL the URL will need to be accessible by your server for file_get_contents() to work, so it probably won't work in a local development environment.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.