Adding block class to widgets

When registering a sidebar, you can set the “before_widget” value to include some classes that WordPress will define. With Gutenberg, you can now use blocks in your sidebars – yay! However, that “before_widget” class by default does not include anything about the block that is used so it can be a challenge to custom style it based on the block. This small code snippet will generate a custom class to add to the widget based on the block name.

Registering a sidebar

register_sidebar( array(
	'name' => 'Footer',
	'id' => 'footer',
	'before_widget' => '<div id="%1$s" class="%2$s">',
	'after_widget' => '</div>',
) );

Custom code to add

add_filter( 'widget_block_dynamic_classname', function( $classname, $block_name ) {
	$classname .= ' ' . sanitize_title( $block_name );
	return $classname;
}, 10, 2);

Before, the end result looked like this:

<div id="block-8" class="widget_block">
...
</div>

Now, our end result looks like this:

<div id="block-8" class="widget_block core-columns">
...
</div>

Now we can use .core-columns CSS class to customize the styling within this block.

About the Author
Derek Ashauer is the sole developer at WP Sunshine. He also does client work through his agency AshWebStudio where he has been working with WordPress since 2005.