get_block_wrapper_attributes()
Generates a string of HTML attributes for the wrapper of the current block, adding to them all styles and capabilities declared via block supports.
The function takes the attributes that WordPress has formed for the block (alignment classes, colors, spacing, custom data, etc.) — and merges them with the values you passed and returns a ready-to-use string of block tag attributes.
The resulting string is already sanitized, so it can be safely inserted directly into the opening HTML tag of the block wrapper.
The method already escapes each value, so do not wrap the result in esc_attr().
Call context
The function should be called only in the place where the block's HTML is actually generated — inside the block render function or in a PHP template that WordPress processes as a block template.
In other words, during the rendering of a specific block instance, when the engine has already:
- Parsed the block JSON metadata and learned which “block supports” are available to it.
- Merged the attributes set by the editor (colors, alignment, custom classes, etc.).
- Passed this data to your PHP code.
If you call it somewhere outside of this context — for example, in a regular hook callback that is not related to the current block — the attributes array will not yet be formed, and the function will return an empty string.
The function works based on WP_Block_Supports::apply_block_supports(), which depends on the correctly filled variable WP_Block_Supports::$block_to_render, which in turn is set before calling the render_callback function in the WP_Block::render() method:
WP_Block_Supports::$block_to_render = $this->parsed_block; $block_content = (string) call_user_func( $this->block_type->render_callback, $this->attributes, $block_content, $this );
No Hooks.
Returns
String.
String— ready-to-insert attributes.Empty string— if there are no final attributes (neither from core nor from you).
Usage
get_block_wrapper_attributes( $extra_attributes );
- $extra_attributes(array)
Additional attributes for the block wrapper as an array of strings. For example:
[ 'class' => 'card card--highlight', 'style' => 'background:#f5f5f5', 'data-id' => 42, 'aria-label' => __( 'Card', 'textdomain' ), ]
By default only
style,class,idandaria-labelare merged. Any other keys are added “as is”.Default: []
Examples
#1 Basic output of a dynamic block
Add wrapper attributes in the block render function.
function myplugin_render_dynamic_block( $attributes, $content ) {
$wrapper_attributes = get_block_wrapper_attributes();
return sprintf(
'<div %1$s>%2$s</div>',
$wrapper_attributes,
$content
);
} #2 Additional custom attributes
Passing a custom class, inline style and a data attribute.
$wrapper_attributes = get_block_wrapper_attributes( [ 'class' => 'card card--highlight', 'style' => 'background: #f5f5f5', 'data-id' => 42, 'aria-label' => 'Card', ] ); echo sprintf( '<section %s>…</section>', $wrapper_attributes );
Changelog
| Since 5.6.0 | Introduced. |