HTeuMeuLeu
HTeuMeuLeu

Reputation: 2751

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

I'm trying to change the default HTML output of a Gutenberg block in WordPress 5.7. For example, the default output of a core/Group block with a paragraph inside is:

<div class="wp-block-group">
    <div class="wp-block-group__inner-container">
        <p>Lorem ipsum dolor sit amet.</p>
    </div>
</div>

I would like to output something like this:

<table role="presentation" class="my-own-custom-class">
    <tr>
        <td>
            <p>Lorem ipsum dolor sit amet.</p>
        </td>
    </tr>
</table>

I've tried using a custom filter on the render_block_core/group hook. But I seem to only be able to add content around what WordPress already outputs. Here’s an example:

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 );

And here’s what I get:

<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>

How do I get rid of the divs generated by WordPress?

Upvotes: 0

Views: 2493

Answers (1)

amarinediary
amarinediary

Reputation: 5441

You can actually loop through blocks by retrieving them from the content using 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
    };
};
?>

Upvotes: 1

Related Questions