Search code examples
wordpresswordpress-gutenberggutenberg-blocks

Wordpress Block.json style handle load all block style


I am using ACF PRO to create custom gutenberg blocks on my classic (PHP based) theme. I am using my a block.json to defined my custom block, and in all of my blocks i have some scripts and styles handles defined as below:

"viewScript": "carrousel-js",
  "style": "carrousel-css",

and another blocks like this :

"viewScript": "accordeon-js",
  "style": "accordeon-css",

Then, in my function.php i have a filter that register those scripts and styles

wp_register_script('accordeon-js', asset('scripts/blocks/accordeon.js')->uri(), array('wp-i18n'), null, true);
wp_register_script('carrousel-js', asset('scripts/blocks/carrousel.js')->uri(), array('wp-i18n'), null, true);
wp_register_style('accordeon-css', asset('styles/blocks/accordeon.css')->uri(), false, null);
wp_register_style('carrousel-css',asset('styles/blocks/carrousel.css')->uri(), false, null);`

On the frontend of my website, my styles and scripts are correctly loaded, however, according to the wordpress documentaton, i was expecting that wordpress load the css and the javascript attached to a block only if this particular block is on the page.

It is working correctly for the scripts, if i have only a carrousel block on a page, it will only load the carrousel.js file, but for the css, it will load the carrousel.css AND the accordeon.css files (and all others blocks styles). What could be causing this issue?


Solution

  • Was having the same issue and after digging around awhile found out that this is a newer opt-in featured.

    https://make.wordpress.org/core/2021/07/01/block-styles-loading-enhancements-in-wordpress-5-8/

    You can opt-in to use this feature with:

    add_filter( 'should_load_separate_core_block_assets', '__return_true' );