Site icon T4Tutorials.com

Wrap each table code inside a div – PHP WordPress

To automatically, wrap each table code inside a div we need to enter the following code inside functions.php file.

It can be useful for many purposes. For exmaple we can make a table responsive width by putting a table tag inside a dive and then assigning the following css to div;

overflow-x: auto !important;

// Add a filter to wrap tables with a custom div
function wrap_tables_with_div($content) {
    // Check if the content contains a table tag
    if (strpos($content, '<table') !== false && strpos($content, '</table>') !== false) {
        // Wrap each table with the custom div
        $content = preg_replace_callback('/<table(.*?)<\/table>/is', function($matches) {
            return '<div class="t4table"><table' . $matches[1] . '</table></div>';
        }, $content);
    }

    return $content;
}

// Add the filter to the_content
add_filter('the_content', 'wrap_tables_with_div');

 

Exit mobile version