Disable the Custom Internal CSS added by theme.json for Certain Pages

I know that WordPress v5.8 has just been released and I have started using the theme.json for managing some basic stuffs on the Gutenberg side. But as I have started using it, I have seen a couple of things:

The custom internal CSS added by WordPress after compiling the theme.json file to each and every page. Does anyone know how to stop adding it on certain pages? For example if I have a custom home page or on archive pages where Gutenberg is not being used, there is no sense to load this internal CSS by WordPress. I was wondering if anyone figured out any filters to conditionally disable the internal CSS output for certain pages.

Here is how it looks:
theme.json internal CSS added by WordPress

P.S.: I’ve already checked the two URLs about the theme.json documentation, but they didn’t help much regarding the queries that I had. These are are links I have already checked:

  • Global Settings & Styles (theme.json)
  • Introducing theme.json in WordPress 5.8

2 Answers
2

We can look into the wp_enqueue_global_styles() function, that calls
wp_should_load_separate_core_block_assets() and see it contains e.g. the should_load_separate_core_block_assets filter but we can’t disable the global styles on the front-end, using this filter because of:

/*
 * Global styles should be printed in the head when loading all styles combined.
 * The footer should only be used to print global styles for classic themes with separate core assets enabled.
 *
 * See https://core.trac.wordpress.org/ticket/53494.
 */
if ( ( ! $separate_assets && doing_action( 'wp_footer' ) ) || ( $separate_assets && doing_action( 'wp_enqueue_scripts' ) ) ) {
    return;
}

where it’s hooked in two places, either header or footer:

// Global styles can be enqueued in both the header and the footer. 
// See https://core.trac.wordpress.org/ticket/53494.
add_action( 'wp_enqueue_scripts', 'wp_enqueue_global_styles' );
add_action( 'wp_footer', 'wp_enqueue_global_styles', 1 );

So ticket 53494 is also useful and the 5.8 dev notes.

For full-site-editing themes with separate block style loading on or off and classical themes with it off, one can dequeue it on the archives with:

add_action( 'wp_enqueue_scripts', function () { 
    is_archive () && wp_dequeue_style ( 'global-styles' );
}, 11 );

since it’s enqueued on wp_enqueue_scripts hook with priority 10.

For classical themes with separate block style loading on:

add_action( 'wp_footer', function () { 
    is_archive () && wp_dequeue_style ( 'global-styles' );
}, 2 );

since it’s enqueued on wp_footer hook with priority 1.

But we note that themes, patterns and other plugins might depend on this.

Leave a Comment