Convert Gutenberg table to Bootstrap table

Gutenberg editor compared to default editor it’s very cool. However, its possibilities aren’t unlimited at the moment. And when we’re dealing with tables, we want that they’ll be responsive. In this case, can help us Bootstrap. But how to use Bootstrap tables and Bootstrap adaptive solutions to Gutenberg editor?

Adding wrapper to Gutenberg’s Table block

Problem: Wrapping Gutenberg block.

Solution: Add next code to functions.php file:

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

function wrap_table_block( $block_content, $block ) {
  if ( 'core/table' === $block['blockName'] ) {
    // Remove <figure> tags, that have 'wp-block-table' class, from content; if we have 2 or more classes this condition will doesn't work
    //preg_match("'<figure class=\"wp-block-table\">(.*?)</figure>'si", $block_content, $match);
    // Remove <figure> tags from content    
    preg_match('/<figure[^>]*>(.*?)<\/figure>/s', $block_content, $match );
        
    if ( $match ) {
        $block_content = $match[1];

        $table_pattern = '/<table/';
        // Add Class To <table> Tag
        $table_class = '<table class="table table-striped"';
        $block_content = preg_replace( $table_pattern, $table_class, $block_content );

        $thead_pattern = '/<thead/';
        // Add Class To <thead> Tag
        $thead_class = '<thead class="table-dark"';
        $block_content = preg_replace( $thead_pattern, $thead_class, $block_content );
    }
    // Add Wrap To <table> Tag
    $block_content = '<div class="table-responsive">' . $block_content . '</div>';
  }
  return $block_content;
}

Sources:

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

Leave Comment

2 Replies to “Adding wrapper to Gutenberg’s Table block”

  • Ilana Child says:

    I simply couldn’t depart your website prior to suggesting that I actually loved the standard information a person supply on your visitors?
    Is gonna be back ceaselessly in order to check up on new posts

  • cruzguerra says:

    This is very attention-grabbing, You’re an excessively skilled blogger.
    I have joined your rss feed and stay up for in search of more of your excellent post.
    Additionally, I have shared your website in my social networks

Your email address will not be published. Required fields are marked *