wordpress snippets last updated   : August 18, 2014
we now have 638 snippets

Shortcode tables with multiple rows and columns

wordpress snippet

Have you have ever wanted to quickly and easily create a simple dataset table? Well adding this snippet to the functions.php of your wordpress theme to enable table shortcodes. Bellow you can see the example shortcode that you can add multiple rows and columns of data separating each row and column with a comma. Thanks to Jean Egan who noticed an issue with the old version.

snippet :  PHP - functions.phpcopy
function simple_table( $atts ) {
    extract( shortcode_atts( array(
        'cols' => 'none',
        'data' => 'none',
    ), $atts ) );
    $cols = explode(',',$cols);
    $data = explode(',',$data);
    $total = count($cols);
    $output .= '<table><tr class="th">';
    foreach($cols as $col):
        $output .= '<td>'.$col.'</td>';
    endforeach;
    $output .= '</tr><tr>';
    $counter = 1;
    foreach($data as $datum):
        $output .= '<td>'.$datum.'</td>';
        if($counter%$total==0):
            $output .= '</tr>';
        endif;
        $counter++;
    endforeach;
        $output .= '</table>';
    return $output;
}
add_shortcode( 'table', 'simple_table' );
source →
snippet :  SHORTCODEcopy
[table cols="names,values" data="name1,25,name2,409"]
source →

Did you like this post? If so please share it with your friends. Thanks!

  • Cmonmail21

    Hie Kevin,
    Thanks for tis code.
    I have a problem, when inserting shortcode in post, it display variables ($x) and not value of variables.
    Thanks for help and sory for my bad english.
    Anne
     

    • http://braginteractive.com Brad Williams

      Change {$col} to ‘. $col . ‘ same for $datum

  • Pingback: Wordpress Table Shortcode Builder › Jean Egan

jqsnipp.com | we just launched jquery snippets website