Abhijit Sood
Abhijit Sood

Reputation: 160

Remove all theme CSS & JS from wp_head Wordpress but not remove the wp admin toollbar

In the template, wp_head() function adds bunch of styles and scripts. Which overrides the other CSS of the theme and in return creates problems.

I tried using a function to remove the CSS and js. It worked but also removes the CSS from the WP admin toolbar.

 function clear_styles_and_scripts() {
     global $wp_scripts;
     global $wp_styles;

foreach( $wp_scripts->queue as $handle ) :

    wp_dequeue_script( $handle );
    wp_deregister_script( $handle );

     endforeach;

foreach( $wp_styles ->queue as $handle ) :

    wp_dequeue_style( $handle );
    wp_deregister_style( $handle );

    endforeach;

 }
  add_action( 'wp_enqueue_scripts', 'clear_styles_and_scripts', 100 );

Upvotes: 4

Views: 1822

Answers (2)

Abhijit Sood
Abhijit Sood

Reputation: 160

This worked.

  function clear_styles_and_scripts() {
  global $wp_scripts;
  global $wp_styles;
  $styles_to_keep = array("wp-admin", "admin-bar", "dashicons", "open-sans");

  foreach( $wp_styles ->queue as $handle ) :
   if ( in_array($handle, $styles_to_keep) ) continue;
    wp_dequeue_style( $handle );
    wp_deregister_style( $handle );

    endforeach;

  }
   add_action( 'wp_enqueue_scripts', 'clear_styles_and_scripts', 100 );

Upvotes: 2

Reza Ramezanpour
Reza Ramezanpour

Reputation: 644

Although I do not recommend to dequeue all scripts and styles, you can check file handle to ignore dequeuing that specific file:

foreach( $wp_styles ->queue as $handle ) :

    // allows admin bar to be added
    if( 'admin-bar' === $handle ) continue;

    wp_dequeue_style( $handle );
    wp_deregister_style( $handle );

endforeach;

Upvotes: 0

Related Questions