So, you love Gutenberg and you want to take advantage of its amazing features on your site’s redesign. You migrate the data and happily realize that everything is in place and all your old content has now become a “classic” block. But then you check the frontend and realize that the block is not wrapped in a div. Apparently, it’s not a bug, it’s a feature, because who wouldn’t want to keep their markup as clean as possible?

When it comes to the classic block, though, this can be quite problematic, as you can have all kinds of elements thrown on your page, with no way to style them all together.

Luckily, there is the render_block() filter, which allows us to render a block into an HTML string. So if, for example, we wanted to wrap Gutenberg’s core/table block in a div, we could easily do something like that:

add_filter( 'render_block', 'wrap_table_block', 10, 2 );

function wrap_table_block( $block_content, $block ) {
  if ( 'core/table' === $block['blockName'] ) {
    $block_content = '<div class="example">' . $block_content . '</div>';
  }
  return $block_content;
}

Unfortunately, with the classic (call me freeform) block, this can get a bit tricky. You see, according to a discussion on Github, it appears that the Classic Block represents pre-Gutenberg content, it’s the no-block block and is merely there for backwards compatibility, which means that it is opted out of comment demarcations by design and there are no plans to wrap it with block tags. In fact, even if you var_dump the $block parameter on our previous function, you will see that when it comes to the freeform block, the blockName attribute returns null instead of the core/freeform which we might expect.

Therefore, in order to target specifically the freeform block, we should check for three things:

  • First, that the blockName is  null.
  • Then, that that it is not empty, since we wouldn’t want to print out an empty wrapper.
  • And finally, make sure that even if it’s not empty, its content isn’t just some accidentally added blank space.

So, eventually, we end up with something like that:

add_filter( 'render_block', 'wrap_classic_block', 10, 2 );

function wrap_classic_block( $block_content, $block ) {
  if ( null === $block['blockName'] && ! empty( $block_content ) && ! ctype_space( $block_content ) ) {
    $block_content = '<div class="example">' . $block_content . '</div>';
  }
  return $block_content;
}

Placing that into your functions.php should allow you to wrap the Gutenberg Classic blog to a div, or whatever markup you like for that matter.

Leave a Reply

Your email address will not be published. Required fields are marked *