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.
Opens WPIDE on
Code
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 add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.