Skip to content

Remove styles and scripts from wp_head

wp_head can add a lot into your header.¬† I was working on improving¬†a site’s loading time and wanted to remove some scripts and styles that weren’t being used in the front end.

First, you can use this code to display all the styles and scripts that have been enqueued:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
function crunchify_print_scripts_styles() {
 
    $result = [];
    $result['scripts'] = [];
    $result['styles'] = [];
 
    // Print all loaded Scripts
    global $wp_scripts;
    foreach( $wp_scripts->queue as $script ) :
       $result['scripts'][] =  $script.' : '.$wp_scripts->registered[$script]->src . ";";
    endforeach;
 
    // Print all loaded Styles (CSS)
    global $wp_styles;
    foreach( $wp_styles->queue as $style ) :
       $result['styles'][] =  $style.' : '.$wp_styles->registered[$style]->src . ";";
    endforeach;
 
    return $result;
}
 
print_r( crunchify_print_scripts_styles() );

Then you can remove specific ones by adding them into the “excess” array and adding this script above your call to wp_head

1
2
3
4
5
6
7
8
9
10
11
function remove_extra_styles() {
	$excess = ['script1','style1'];
 
	foreach($excess as $e) {
		wp_deregister_style($e);
		wp_dequeue_style($e);
		wp_dequeue_script($e);
		wp_deregister_script($e);		
	}
}
add_action( 'wp_enqueue_scripts', 'remove_extra_styles', 100 );

Sources:

https://wordpress.stackexchange.com/questions/233140/how-can-i-get-a-list-of-all-enqueued-scripts-and-styles
https://wordpress.stackexchange.com/questions/246547/remove-all-theme-css-js-from-wp-head-but-only-for-1-page-template

 

Published inPHPScripting

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *