# Table From Comma-Separated Text Shortcode

> Adds a [data_table] shortcode that turns comma-separated lines typed between the tags into a clean, accessible HTML table with a header row, which is much quicker than building tables by hand.

- Type: PHP
- Runs: Run everywhere
- Category: [Content](https://wpide.com/library/category/content/)
- Tags: shortcodes, tables, data
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/csv-table-shortcode/

## Code

```php
add_action( 'init', function () {
    add_shortcode( 'data_table', function ( $atts, $content = '' ) {
        $atts = shortcode_atts( array( 'delimiter' => ',', 'header' => 'yes', 'caption' => '' ), $atts, 'data_table' );

        // Undo wpautop line breaks and paragraphs.
        $text  = preg_replace( '#<br\s*/?>|</p>\s*<p>#i', "\n", $content );
        $text  = trim( wp_strip_all_tags( $text ) );
        $lines = array_filter( array_map( 'trim', preg_split( '/\r\n|\r|\n/', $text ) ), 'strlen' );
        if ( ! $lines ) {
            return '';
        }

        $delimiter = substr( (string) $atts['delimiter'], 0, 1 );
        $rows      = array_map( function ( $line ) use ( $delimiter ) {
            return array_map( 'trim', str_getcsv( html_entity_decode( $line, ENT_QUOTES ), $delimiter ? $delimiter : ',', '"', '\\' ) );
        }, array_values( $lines ) );

        $html = '<div class="wpide-data-table" style="overflow-x:auto"><table>';
        if ( '' !== $atts['caption'] ) {
            $html .= '<caption>' . esc_html( $atts['caption'] ) . '</caption>';
        }
        if ( 'yes' === $atts['header'] ) {
            $head  = array_shift( $rows );
            $html .= '<thead><tr>' . implode( '', array_map( function ( $cell ) {
                return '<th scope="col">' . esc_html( $cell ) . '</th>';
            }, $head ) ) . '</tr></thead>';
        }
        $html .= '<tbody>';
        foreach ( $rows as $row ) {
            $html .= '<tr>' . implode( '', array_map( function ( $cell ) {
                return '<td>' . esc_html( $cell ) . '</td>';
            }, $row ) ) . '</tr>';
        }

        return $html . '</tbody></table></div>';
    } );
} );
```

## Notes

Example [data_table caption="Opening hours"]Day, Hours<br>Monday, 9-17[/data_table]; use delimiter=";" for semicolons and header="no" to skip the header row.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Table From Comma-Separated Text Shortcode" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
