Performance PHP Intermediate

Skip Block CSS on Pages Without Blocks

On classic and page-builder themes, stop loading the block library stylesheet on pages that contain no blocks.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 15 lines
add_action( 'wp_enqueue_scripts', function (): void {
	// Block themes build every page from blocks, so they always need these styles.
	if ( wp_is_block_theme() || ! is_singular() ) {
		return;
	}

	$post = get_queried_object();
	if ( ! $post instanceof WP_Post || has_blocks( $post->post_content ) ) {
		return;
	}

	wp_dequeue_style( 'wp-block-library' );
	wp_dequeue_style( 'wp-block-library-theme' );
	wp_dequeue_style( 'classic-theme-styles' );
}, 100 );

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

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.

Don't use with Block themes. Check the notes below before adding it.

WordPress loads the block library stylesheet on every page so blocks look right. Sites built with a page builder such as Bricks, or older posts written in the classic editor, often have pages with no blocks at all. This snippet skips that stylesheet on those pages.

How it works

On single posts and pages, has_blocks() checks the content for block markup. If there’s none, the snippet removes wp-block-library, the optional wp-block-library-theme and classic-theme-styles, which only styles blocks on classic themes.

It does nothing at all on block themes. Their headers, footers and templates are made of blocks even when the post content isn’t, so they always need the styles.

The previous version also removed global-styles, the CSS WordPress generates from theme.json. That stylesheet holds colours, fonts and spacing presets your theme and page builder may rely on even without blocks, and removing it could change how the whole page looked.

Things to watch

  • Blocks placed outside the post content, such as in a widget area or a reusable section in a sidebar, aren’t detected. Check those pages after adding the snippet.
  • Archive and search pages are left alone, because they can show block content from many posts.

How to test it

Open a page built without blocks and view the source: wp-block-library-css should be gone. Open a post written in the block editor and it should still be there.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only