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

I am creating a Wordpress plugin.

I created the basis for this, and everything is set up correctly.

I tried looking at this and this to find out if I can request and get all the scripts (.js files) from the header and footer.

I thought this was the best feature, but the result is not happening correctly.

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

So let this be 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 should look for .css and .js files and replace the string with others. To get the result:

 <!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 really need to get a name and path for these files.

I think I can use a regex, but I don’t know how to load it with get_header and get_footer (if these are the correct functions)

+4
source share
2 answers

You can access the highlighted script and styles using the global variables $wp_scripts and $wp_styles .

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

+1
source

It would be much better, instead of removing the corresponding markup after receiving it from the get_header() and get_footer() functions, to remove all styles and / or scripts so that they never print there.

You can get the file path by looking at the $wp_styles / $wp_scripts objects' registered property. Then you can get the file name 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 that need to be put in place, just use wp_enqueue_style() and wp_enqueue_script() .

+3
source

All Articles