How to get .js and .css files and replace them

I’m creating a WordPress plugin.

I’ve created the basis for this and all is correctly set up.

Read More

I’ve tried looking at this and this to see if I could request and get all of the scripts (.js files) from the header and footer.

I thought that was the best function but the result is not happening right.

I basically want to get the JS and CSS files and replace with another string.

So let’s say this is my page:

<!DOCTYPE html>
<html>
<head>
    <title>Page</title>
    <link rel="stylesheet" href="http://www.example.com/mycss.css" />
</head>
<body>

<script type="text/javascript" src="http://www.example.com/myscript.js"></script>
<script type="text/javascript" src="http://www.example.com/another_script.js"></script>
</body>
</html>

My function has to look for the .css and .js files and replace the string with other stuff. So that the result would be:

<!DOCTYPE html>
<html>
<head>
    <title>Page</title>
    <mytag>Here was contained a CSS from http://www.example.com/mycss.css</mytag>
</head>
<body>

<mytag>Here were contained 2 JS from http://www.example.com/myscript.js and http://www.example.com/another_script.js</mytag>
</body>
</html>

EDIT
I actually have to get the name and path for those files.

I think I can use a regexp but I don’t know how to load it using get_header and get_footer (if those are the right functions)

Related posts

2 comments

  1. It would make much more sense, rather than removing the relevant markup after receiving it from get_header() and get_footer() functions, to dequeue all styles and/or scripts so they are never printed there in the first place.

    You can get the path for the file by looking back at the $wp_styles/$wp_scripts objects’ registered property. You can then go on to get the filename using basename():

    function dequeue_all_styles() {
        global $wp_styles;
    
        foreach( $wp_styles->queue as $handle ){
            wp_dequeue_style($handle);
            $src = $wp_styles->registered[$handle]->src;
            $filename = basename($src);
        }
    }
    add_action( 'wp_print_styles', 'dequeue_all_styles', 100 );
    
    function dequeue_all_scripts() {
        global $wp_scripts;
    
        foreach( $wp_scripts->queue as $handle ){
            wp_dequeue_script($handle);
            $src = $wp_scripts->registered[$handle]->src;
            $filename = basename($src);
        }
    }
    add_action( 'wp_print_scripts', 'dequeue_all_scripts', 100 );
    

    If you have other styles and scripts to put in their place, simply use wp_enqueue_style() and wp_enqueue_script().

  2. You can access the enqueued script and styles by using $wp_scripts and $wp_styles global variables.

    See the class reference for WP_Styles and WP_Scripts for available methods and properties.

Comments are closed.