Last active
November 16, 2018 10:15
-
-
Save nielsvr/e463ed573bb551ac63ea9d0589695ed6 to your computer and use it in GitHub Desktop.
Enqueue styles in Gutenberg only if the blocks are used on the post/page
This file contains hidden or 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 | |
add_action('enqueue_block_assets', 'maybe_enqueue_scripts_and_styles' ); | |
function maybe_enqueue_scripts_and_styles() { | |
// Map blockname with CSS filename | |
$styles = array( | |
"basic" => "basic" | |
); | |
// Extend with post types you use gutenberg on | |
if( !is_admin() && is_singular( array( 'post' ) ) ) { | |
$post = get_post(); | |
if ( gutenberg_content_has_blocks( $post->post_content ) ) { | |
$blocks = gutenberg_parse_blocks( $post->post_content ); | |
foreach( $blocks AS $block ) { | |
// If you use ACF to register blocks, remove the acf prefix | |
$blockname = str_replace('acf/', '', $block['blockName']); | |
if( array_key_exists( $blockname, $styles ) ) { | |
$filename = $styles[ $blockname ]; | |
wp_enqueue_style( "block-{$blockname}-css", get_stylesheet_directory_uri()."/css/blocks/{$filename}.css" ); | |
} | |
} | |
} | |
} | |
// Enqueue everything in the admin view | |
if( is_admin() ) { | |
foreach( $styles AS $blockname => $style ) { | |
wp_enqueue_style( "block-{$blockname}-css", get_stylesheet_directory_uri()."/css/blocks/{$style}.css" ); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment