How to dequeue / deregister any theme styles and scripts

The tricky thing is knowing whether or not a particular script or style was enqueued by the theme.

Themes and plugins both use the same hooks and functions, so they’re not explicitly labelled in any way as belonging to a specific theme or plugin. This means that the only way to know whether a script or style is from the theme is to check the URL to see whether the the script/style’s URL is pointing to somewhere in the theme directory.

One way you can do this is to loop over $wp_scripts->registered and $wp_styles->registered, and check the URL of each script and style against get_theme_root_uri() which tells you the URL to the themes folder. If the script/style appears to be inside that folder, you can dequeue it:

function wpse_340767_dequeue_theme_assets() {
    $wp_scripts = wp_scripts();
    $wp_styles  = wp_styles();
    $themes_uri = get_theme_root_uri();

    foreach ( $wp_scripts->registered as $wp_script ) {
        if ( strpos( $wp_script->src, $themes_uri ) !== false ) {
            wp_deregister_script( $wp_script->handle );
        }
    }

    foreach ( $wp_styles->registered as $wp_style ) {
        if ( strpos( $wp_style->src, $themes_uri ) !== false ) {
            wp_deregister_style( $wp_style->handle );
        }
    }
}
add_action( 'wp_enqueue_scripts', 'wpse_340767_dequeue_theme_assets', 999 );

This will only work if the stylesheet or script is inside the theme. If the theme is enqueueing scripts or styles from a CDN, then I’m not sure if it’s possible to target those.

Leave a Comment