问题描述
我正在尝试更改 wordpress 5.7 中古腾堡块的默认 HTML 输出。例如,带有段落的 core/Group
块的默认输出是:
<div class="wp-block-group">
<div class="wp-block-group__inner-container">
<p>Lorem ipsum dolor sit amet.</p>
</div>
</div>
<table role="presentation" class="my-own-custom-class">
<tr>
<td>
<p>Lorem ipsum dolor sit amet.</p>
</td>
</tr>
</table>
我尝试在 render_block_core/group
挂钩上使用自定义过滤器。但我似乎只能围绕 wordpress 已经输出的内容添加内容。举个例子:
function my_group_block_wrapper( $block_content,$block ) {
$content = '<table role="presentation" class="my-own-custom-class"><tr><td>' . $block_content . '</td></tr></table>';
return $content;
}
add_filter( 'render_block_core/group','my_group_block_wrapper',10,2 );
这是我得到的:
<table role="presentation" class="my-own-custom-class">
<tr>
<td>
<div class="wp-block-group">
<div class="wp-block-group__inner-container">
<p>Lorem ipsum dolor sit amet.</p>
</div>
</div>
</td>
</tr>
</table>
解决方法
您实际上可以通过使用 parse_blocks()
从内容中检索块来遍历块。
从内容字符串中解析块。
<?php
if ( ! empty( get_the_content() ) ) { //... check if the content is empty
$blocks = parse_blocks( get_the_content() ); //... retrieve blocks from the content
foreach ( $blocks as $block ) { //... loop through blocks
echo wp_strip_all_tags( render_block( $block ) ); //... strip all html and render blocks
};
};
?>