Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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).

share|improve this question
add comment

1 Answer

up vote 3 down vote accepted

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' );
share|improve this answer
    
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 '11 at 10:55
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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