Are you looking for a way to quickly create a simple dataset table? While there’s probably a plugin for this, we have created a quick code snippet that you can use to enable shortcode tables with multiple rows and columns in WordPress.
Instructions:
All you have to do is add this code to your theme’s functions.php file or in a site-specific plugin:
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' );
[table cols="names,values" data="name1,25,name2,409"]
Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly add code snippets in WordPress, so you don’t accidentally break your site.
If you liked this code snippet, please consider checking out our other articles on the site like: 19 best WordPress plugins for photographers and how to easily create a survey in WordPress.
Hi guys,
This is a great snippet to easily create simple tables. I know the article is a little dated but I see Alex comment is 4 months old so my comment could be still useful to somene..
The Snippet should be slightly modified declaring $output = ”; just before
extract( shortcode_atts( array(
Full shortcode function below.
function simple_table( $atts ) {
$output = '';
extract( shortcode_atts( array(
'cols' => 'none',
'data' => 'none',
), $atts ) );
$cols = explode(',',$cols);
$data = explode(',',$data);
$total = count($cols);
$output .= '';
foreach($cols as $col):
$output .= ''.$col.'';
endforeach;
$output .= '';
$counter = 1;
foreach($data as $datum):
$output .= ''.$datum.'';
if($counter%$total==0):
$output .= '';
endif;
$counter++;
endforeach;
$output .= '';
return $output;
}
add_shortcode( 'table', 'simple_table' );
Hi guys,
when I add the code to my functions.php the parameters of [table cols="names,values" data="name1,25,name2,409"] do not get passed and it outputs none, none. You know why that is?
Thanks
[…] because I found this post by Kevin Chard. However, I encountered results that weren’t quite […]
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
Change {$col} to ‘. $col . ‘ same for $datum