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} ";
    endforeach;

    $output .= "<br>";

    $counter = 1;
    foreach($data as $datum):
        $output .= "| {$datum} ";
        if($counter%$total==0):
            $output .= "<br>";
        endif;
        $counter++;
    endforeach;

    return $output;

}
add_shortcode( 'myproduct', 'myproduct_func' );

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *