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:

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

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!

1 Answer 1


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.

  • You can try to derive the path from the URL though.
    – swissspidy
    Feb 2, 2018 at 12:40
  • Thanks! I made a modification to verify that the file exists and also to load the local file: if ( $handle === 'script-handle' ) { $url = explode(get_site_url(), $src); $path = strtok($url[1], '?'); $path = str_replace('/', DIRECTORY_SEPARATOR, $path); $complete_path = $_SERVER['DOCUMENT_ROOT'].$path; if(file_exists($complete_path)) { $script = sprintf( '<script type="text/javascript">%s</script>', file_get_contents( $complete_path ) ); } } Feb 2, 2018 at 13:28

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.