Last active
September 13, 2021 11:56
-
-
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()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note: style.min.css is used, not style-rtl.min.css which is also available