WordPress Table Shortcode Builder

If you’re like me, you’ve probably needed to create nice looking tables for your WordPress hosted site but haven’t found a good shortcode for it. Well, today’s your lucky day (and mine)!

That’s because I found this post by Kevin Chard. However, I encountered results that weren’t quite favorable:

Variables not parsed - table contents

As you can see, it wasn’t parsing the variables at all. So, I made a few minor adjustments to his code.

I changed the following code:

[php]$Output .=[/php]

to:

[php]echo[/php]

and instead, concatinated the mixed html and variables in strings, like this:

[php]echo ‘<td>’.$col.'</td>’;[/php]

And had glorious results:

Perfect! Variables parsed - table contents

Here’s the full code, placed within my theme’s functions.php file:

[php]function simple_table( $atts ) {

extract( shortcode_atts( array(
‘cols’ => ‘none’,
‘data’ => ‘none’,
), $atts ) );
$cols = explode(‘,’,$cols);
$data = explode(‘,’,$data);
$total = count($cols);
echo ‘<table><tr class="th">’;
foreach($cols as $col):
echo ‘<td>’.$col.'</td>’;
endforeach;
echo ‘</tr><tr>’;
$counter = 1;
foreach($data as $datum):
echo ‘<td>’.$datum.'</td>’;
if($counter%$total==0):
echo ‘</tr>’;
endif;
$counter++;
endforeach;
echo ‘</table>’;
}
add_shortcode( ‘mytable’, ‘simple_table’ );[/php]

And, here is the shortcode call from within the WP page:

[code][mytable cols="name,quantity,price" data="name1,5,2.00,name2,3,3.25"][/code]

You can export comma separated values (CSV) from your excel doc and you only have to separate the top (header) row to ensure the appropriate number of columns are created.

The two drawbacks I see with this shortcode are:

  1. Must have equal columns to avoid rolling overflow.
  2. Not able to create table cells that span columns or rows.

But it’s a great start.


Update: Kevin noticed the last output call I had inadvertently left in from his code was unnecessary. Thank you for your keen eye to the code, Kevin!

[php]return $output;[/php]

Thank you again, Kevin!

0 thoughts on “WordPress Table Shortcode Builder

  1. Hi Jean,
    Ooops was not aware I made that mistake, I updated the post with a thanks to you and a link back. Great article. I’m now following your RSS feed, looking forward to some great posts by you.
    Cheers

  2. Hi Kevin – thanks for the check-in & for updating your post. I appreciate being able to work off your helpful code.

    Thanks also for subscribing to my RSS feed. I will often post non-WordPress things to my blog, so I wouldn’t feel badly if you chose not to check in. If you are patient and not bothered by other subjects in between, you will find I always use the word “WordPress” in the title when it relates to WP. I look forward to connecting with you again on your site, as well! WPSnip.com looks very helpful!

    It’s a pleasure to meet your acquaintance today.

Leave a Comment