首页 > 解决方案 > 如何更改 WordPress 中 Gutenberg 块的默认 HTML 输出?

问题描述

我正在尝试更改 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?

标签: wordpresswordpress-themingwordpress-gutenberggutenberg-blocks

解决方案


您实际上可以通过使用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
    };
};
?>

推荐阅读