ACF Blocks: Using get_block_wrapper_attributes()

Last updated Oct 3, 2023


The get_block_wrapper_attributes() function allows you to use the styles built by WordPress’ native supports for a block, such as background and text colors, padding, margin, etc.

In the block editor, this is automatically output for you, on the wrapper WordPress adds around your block:

An example of the wrapper WordPress adds around your block in the block editor when using get_block_wrapper_attributes().  

For this reason, you shouldn’t try to always apply get_block_wrapper_attributes in your ACF Block PHP template. If you try to use that function when your block is rendered in the editor, you’ll get a PHP warning when your block is rendered there and no output due to the way ACF blocks are rendered, isolated from the rest of the page.

Instead, use ACF’s $is_preview variable to know when your block is being output on the frontend, and then use get_block_wrapper_attributes() to add all the styles selected for your block.

An example of get_block_wrapper_attributes() applied at the correct point.  

The following code makes sure we’re not in preview mode before outputting the wrapper attributes.

<?php $attrs = $is_preview ? ' ' : get_block_wrapper_attributes(); ?>
    data-demo-hint="This is the outer wrapper in my template"
    id="<?php echo esc_attr( $id ); ?>"
    <?php echo $attrs; ?>
   // Block output goes here.

This does mean your DOM structures are slightly different on the backend and the frontend, as your styles are applied one layer deeper. If that’s an issue, you can get around it by adding a new wrapper element to contain your styles, and apply it only to the frontend view:

<?php if ( ! $is_preview ) { ?>
    <div id="<?php echo esc_attr( $id ); ?>" <?php echo get_block_wrapper_attributes(); ?>>
<?php } ?>
    // Standard block template goes here
<?php if ( ! $is_preview ) { ?>
<?php } ?>