如何更改 WordPress 中 Gutenberg 块的默认 HTML 输出?

How to change the default HTML output of a Gutenberg block in WordPress?

我正在尝试更改 WordPress 5.7 中 Gutenberg 块的默认 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>

如何删除 WordPress 生成的 div?

您实际上可以通过使用 parse_blocks() 从内容中检索块来循环块。

Parses blocks out of a content string.

<?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
    };
};
?>