Remove External scripts & styles from WordPress Admin Page

This tutorial will talk about dequeue hack to remove external plugins’ and themes’ scripts and styles from your WordPress admin page.

In some cases, plugins and themes may enqueue scripts and styles all over the admin area which can potentially break your own admin page. I have faced several cases, where a particular plugin would insert its own jQuery UI styling on all WordPress admin pages and it would inevitably break eForm styling.

To fix this, I have come up with a quick code, which would check all scripts and styles, and will dequeue everything that isn’t related to WordPress core admin or the plugin page itself. Use it with caution.

 

add_action( 'admin_enqueue_scripts', 'sandbox_assets', 99, 1 );

/**
 * Remove all external styles and scripts coming from other plugins
 * which may cause compatibility issue, especially with React
 *
 * @return void
 */
public function sandbox_assets() {
	$assets = [
		'styles'  => wp_styles(),
		'scripts' => wp_scripts(),
	];
	foreach ( $assets as $type => $asset ) {
		foreach ( $asset->registered as $handle => $dep ) {
			$src = $dep->src;
			// test if the src is coming from /wp-admin/ or /wp-includes/ or /wp-fsqm-pro/.
			if (
				is_string( $src ) && // For some built-ins, $src is true|false
				strpos( $src, 'wp-admin' ) === false &&
				strpos( $src, 'wp-include' ) === false &&
				// things below are specific to your plugin, so change them
				strpos( $src, 'eform-' ) === false &&
				strpos( $src, 'woocommerce' ) === false &&
				strpos( $src, 'jetpack' ) === false &&
				strpos( $src, 'debug-bar' ) === false &&
				strpos( $src, 'fsqm-' ) === false
			) {
				if ( 'scripts' === $type ) {
					wp_dequeue_script( $handle );
				} else {
					wp_dequeue_style( $handle );
				}
			}
		}
	}
}

I hope it helps.