Im trying to build a shortcode which calls an HTML table with a fixed number of columns and a variable number of rows depending on the context.

Its hard to manage — or even build, multiple tables over and over through HTML. I've had no trouble creating fixed columns and rows through shortcodes.

To illustrate through the usage of a trivial example:

Lets assume i build a table with 4 columns and 1 row.

The 4 columns will contain the following table headers:

  1. Product name
  2. Quantity
  3. Price per item
  4. Total price

What if i wanted to create multiple rows (Product 1, Product 2 etc..), if at all possible, how can i build a shortcode that enables me to add more rows as i see fit — without creating a separate shortcode for table rows (been there).

1 Answer 1


pass your data in single variables delimited by some char:

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

then explode it into an array and output. I didn't bother with table markup here, but you get the idea:

function myproduct_func( $atts ) {
    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} ";

    $output .= "<br>";

    $counter = 1;
    foreach($data as $datum):
        $output .= "| {$datum} ";
            $output .= "<br>";

    return $output;

add_shortcode( 'myproduct', 'myproduct_func' );
  • Its pretty slick milo. It worked perfectly, i knew i had to implement foreach but i couldn't get a grasp on how WordPress proceses shortcodes. Thanks alot for looking into it.
    – VicePrez
    May 14, 2011 at 10:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.