Skip to content

Commit

Permalink
Add: Simple way to register block styles.
Browse files Browse the repository at this point in the history
  • Loading branch information
jorgefilipecosta committed Jul 18, 2019
1 parent c323235 commit 7c5bdf7
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 2 deletions.
59 changes: 58 additions & 1 deletion lib/blocks.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?php
/**
* Block registration functions.
* Block and style registration functions.
*
* @package gutenberg
*/
Expand Down Expand Up @@ -45,3 +45,60 @@ function gutenberg_reregister_core_block_types() {
}
}
add_action( 'init', 'gutenberg_reregister_core_block_types' );

/**
* Registers a new block style.
*
* @param string $block_name Block type name including namespace.
* @param array $style_properties Array containing the properties of the style name, label, style (name of the stylesheet to be enqueued), inline_style (string containing the CSS to be added).
*/
function register_block_style( $block_name, $style_properties ) {
if ( isset( $style_properties['style'] ) ) {
$style_handle = $style_properties['style'];
unset( $style_properties['style'] );
/** This action is documented in wp-admin/admin-footer.php */
// phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
add_action(
'enqueue_block_assets',
function() use ( $style_handle ) {
wp_enqueue_style( $style_handle );
},
30
);
}

if ( isset( $style_properties['inline_style'] ) ) {
$inline_style = $style_properties['inline_style'];
unset( $style_properties['inline_style'] );
add_action(
'enqueue_block_assets',
function() use ( $inline_style ) {
wp_add_inline_style( 'wp-block-library', $inline_style );
}
);
}

add_action(
'enqueue_block_assets',
function() use ( $block_name, $style_properties ) {
wp_add_inline_script(
'wp-blocks',
sprintf(
implode(
"\n",
array(
'( function() {',
' wp.blocks.registerBlockStyle( \'%s\', %s );',
'} )();',
)
),
$block_name,
wp_json_encode( $style_properties )
),
'after'
);
}
);

}

2 changes: 1 addition & 1 deletion phpcs.xml.dist
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
<description>Sniffs for WordPress plugins, with minor modifications for Gutenberg</description>

<rule ref="PHPCompatibility"/>
<config name="testVersion" value="5.2-"/>
<config name="testVersion" value="5.6-"/>

<rule ref="WordPress-Core"/>
<rule ref="WordPress-Docs"/>
Expand Down

0 comments on commit 7c5bdf7

Please sign in to comment.