Stop WooCommerce loading its styles and cart scripts on blog posts and other pages that don't sell anything, without breaking order attribution.
add_action( 'wp_enqueue_scripts', function (): void {
// Do nothing if WooCommerce isn't active.
if ( ! function_exists( 'is_woocommerce' ) ) {
return;
}
// Keep everything on store pages.
if ( is_woocommerce() || is_cart() || is_checkout() || is_account_page() ) {
return;
}
// Keep everything on pages that contain WooCommerce blocks or shortcodes.
$post = get_post();
if ( $post && ( str_contains( $post->post_content, 'wp:woocommerce/' ) || has_shortcode( $post->post_content, 'products' ) || has_shortcode( $post->post_content, 'product_page' ) ) ) {
return;
}
foreach ( [ 'woocommerce-general', 'woocommerce-layout', 'woocommerce-smallscreen', 'woocommerce-inline', 'wc-blocks-style' ] as $style ) {
wp_dequeue_style( $style );
}
foreach ( [ 'woocommerce', 'wc-add-to-cart', 'wc-cart-fragments' ] as $script ) {
wp_dequeue_script( $script );
}
}, 99 );
Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.
WooCommerce loads its stylesheets and cart scripts on every page of your site, including blog posts and the About page. On content-heavy sites that’s extra CSS and JavaScript on most visits for no benefit. This snippet keeps them on store pages only.
The callback runs late on wp_enqueue_scripts, after WooCommerce has queued its files. It first checks that WooCommerce is active; the previous version called is_woocommerce() directly, which caused a fatal error if WooCommerce was ever deactivated. It then leaves everything alone on the shop, product, category, cart, checkout and account pages, and on any page that contains WooCommerce blocks or product shortcodes.
On all other pages it removes WooCommerce’s main stylesheets, the block styles and the add-to-cart and cart fragments scripts.
WooCommerce’s order attribution scripts (sourcebuster-js and wc-order-attribution) are left in place. They record which page and campaign a visitor arrived from, so removing them from blog posts would make your marketing reports wrong.
Open a blog post, view the source and search for woocommerce-general. It shouldn’t be there. Then open the shop and a product page and check they still look and work as normal.