Skip to content

Instantly share code, notes, and snippets.

@ramonfincken
Last active September 13, 2021 11:56
Show Gist options
  • Save ramonfincken/3493a836014b6cc7d846dd4804d94ece to your computer and use it in GitHub Desktop.
Save ramonfincken/3493a836014b6cc7d846dd4804d94ece to your computer and use it in GitHub Desktop.
Outputs minified WP Core Block styles css in footer, only the blocks you actually use in the_content()
<?php
/**
* Outputs minified WP Core Block styles css in footer, only the blocks you actually use in the_content()
* Needs wp_deregister_script( 'wp-block-library' );
*
* @author Ramon Fincken, ManagedWPHosting.nl
*
* @param string $block_content
* @param array $parsed_block
* @return string
*/
function mp_render_block_styles ( string $block_content, array $parsed_block ) {
global $mp_block_css;
if( !substr_count( $parsed_block['blockName'], 'core/' ) ) {
return $block_content;
}
// Set
if( !is_array( $mp_block_css ) ) {
$mp_block_css = [];
}
$t = str_replace( 'core/', '', $parsed_block['blockName'] );
// Set up CSS data array
if( isset( $mp_block_css[$t] ) ) {
return $block_content;
}
// Add to global array for usage in footer
$file = ABSPATH . WPINC . '/blocks/'.$t.'/style.min.css';
if( !file_exists( $file ) ) {
return $block_content;
}
$mp_block_css[$t] = file_get_contents( $file );
// Output all CSS just the once
if( count( $mp_block_css ) == 1 ) {
add_action( 'wp_footer', function( ) { global $mp_block_css; echo '<style>'; foreach( $mp_block_css as $css) { echo $css. ' '; } echo '</style>'; } );
}
return $block_content;
}
add_filter( 'render_block', 'mp_render_block_styles', 0, 2 );
@ramonfincken
Copy link
Author

Note: style.min.css is used, not style-rtl.min.css which is also available

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment