Wrap the Gutenberg Table Block with Bootstrap Classes Using render_block Filter

Convert the Gutenberg table to a Bootstrap table

Compared to the classic editor, Gutenberg is very cool, but its possibilities are not unlimited yet. When we work with tables, we want them to be responsive and styled like the rest of the site. Bootstrap can help here. But how do we use Bootstrap tables and the responsive wrapper with the Gutenberg Table block?

Problem: Add Bootstrap classes and a responsive wrapper to the Gutenberg Table block.

Solution: The render_block filter receives the HTML of every block before it is output. For the core/table block we add the classes to <table> and <thead> and wrap the table in <div class="table-responsive">. Add to functions.php:

<?php
add_filter( 'render_block', 'wrap_table_block', 10, 2 );

function wrap_table_block( $block_content, $block ) {
    if ( 'core/table' !== $block['blockName'] ) {
        return $block_content;
    }

    // Add Bootstrap classes to <table>, keeping the classes it already has
    $block_content = preg_replace_callback( '/<table([^>]*)>/', function ( $m ) {
        if ( preg_match( '/class="([^"]*)"/', $m[1], $c ) ) {
            return '<table' . str_replace( $c[0], 'class="' . trim( $c[1] . ' table table-striped' ) . '"', $m[1] ) . '>';
        }
        return '<table class="table table-striped"' . $m[1] . '>';
    }, $block_content, 1 );

    // Dark header row
    $block_content = preg_replace( '/<thead>/', '<thead class="thead-dark">', $block_content, 1 );

    // Wrap the table for horizontal scrolling on small screens
    $block_content = preg_replace( '#<table.*?</table>#s', '<div class="table-responsive">$0</div>', $block_content, 1 );

    return $block_content;
}

The table block outputs <figure class="wp-block-table"><table>…</table></figure>. My first version removed the <figure> completely, but the table caption (<figcaption>) is also inside it, so it was lost. Here the wrapper goes inside the figure, and the caption stays.

The <thead> exists only when “Header section” is enabled in the block settings. If the editor chose the “Stripes” style, the block adds its own stripes too, so with table-striped it is better to keep the default style.

The filter works only on the front end, so the editor still shows the default table. If you want the same look in the editor, load the Bootstrap styles there with add_editor_style().

Update (2021): In Bootstrap 5 the dark header class is table-dark instead of thead-dark.

Sources:

  1. https://www.gsarigiannidis.gr/adding-a-div-wrapper-to-gutenberg-s-classic-block
  2. https://wordpress.org/support/topic/wrapping-gutenberg-block/