As you can see by my last reply I needed some solution to this. Now after digging into the filters that are inside the render function I have used the following:
This is within a class so you may need to change this if its just used in a functions.php file but I will try to explain how I am using this as its not exactly what you need.
So the first thing is that only some of my page blocks are wrapped look in the “wrap_core_blocks” function which are core blocks are are going to need to be wrapped
What I needed was a way to add a wrap to paragraphs or other blocks but only when not within another block like columns / groups.
So I used another filter render_block_data
this is only triggered on groups and column blocks and it will loop over all of the innerBlocks and add the attribute hasParent this allows me to check it for what I need.
There is much that can be improved here but I spent far too long on this already and this will do for what I need, perhaps you or others may be able to make a better go of this?
add_filter('render_block', [$this, 'wrap_core_blocks'], 10, 2);
add_filter('render_block_data', [$this, 'block_data_pre_render'], 10, 2);
public function wrap_core_blocks($block_content, $block)
{
$core_blocks = [
'core/image',
'core/paragraph',
'core-embed/youtube',
'core/embed',
'core/title',
'core/quote',
'core/pullquote',
'core/heading',
'core/group'
];
if (
in_array($block['blockName'], $core_blocks, true) &&
!is_admin() &&
!wp_is_json_request() &&
!isset($block['attrs']['hasParent'])
) {
$html = '';
$html .= '<div class="container-md clearfix">' . "\n";
$html .= $block_content;
$html .= '</div><!--/ .container -->' . "\n";
return $html;
}
return $block_content;
}
public function block_data_pre_render($parsed_block, $source_block)
{
$core_blocks = [
'core/group',
'core/column'
];
if (
in_array($source_block['blockName'], $core_blocks, true) &&
!is_admin() &&
!wp_is_json_request()
) {
$parsed_block['attrs']['hasChild'] = 1;
array_walk($parsed_block['innerBlocks'], [$this, 'inner_block_looper']);
}
return $parsed_block;
}
public function inner_block_looper(&$itm, $key)
{
if ($key === 'attrs') {
$itm['hasParent'] = 1;
}
if (is_array($itm)) {
array_walk($itm, [$this, 'inner_block_looper']);
}
}
]]>