1

I have the following code

 function stock_agenda() {

        $days = json_decode(file_get_contents('json_file'));

        unset($days[0]);

        return  '<table class="table">
   <thead>
     <tr>
      <th> Title </th>
      <th>Content</th>
      <th>Date</th>
     </tr>
    </thead>
    <tbody>
     '. foreach($days as $day){.'
      <tr>
       <td>'.$day[0].'</td>
       <td>'.$day[1].'</td>
       <td>'.$day[2].'</td>
      </tr>
     '. }.'
     </tbody>
</table>' ;
    }

How to I assign it to a shortcode? If I write foreach inside the return method I get an error.

2
  • 1
    its because you echo inside the shortcode. show your full shortcode. and you can use ob_start() and ob_get_clean() to get the buffer data. and return him...
    – Shibi
    Nov 10, 2017 at 13:28
  • @Shibi I edit my question
    – loliki
    Nov 10, 2017 at 14:43

2 Answers 2

3

As I said in the comment you can use buffering like this

function stock_agenda() {
    $days = json_decode(file_get_contents('json_file'));
    unset($days[0]);
    ob_start(); // start buffer
    ?>
    <table class="table">
        <thead>
            <tr>
                <th> Title </th>
                <th>Content</th>
                <th>Date</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach($days as $day) { ?>
            <tr>
                <td><?php echo $day[0]; ?></td>
                <td><?php echo $day[1]; ?></td>
                <td><?php echo $day[2]; ?></td>
            </tr>
            <?php } ?>
        </tbody>
    </table>
    <?php
    $output = ob_get_clean(); // set the buffer data to variable and clean the buffer
    return $output;
}
1
  • Works like a charm, thanks man, I will read more about buffering.
    – loliki
    Nov 10, 2017 at 14:54
0

You can use:

function stock_agenda() {

    $days = json_decode(file_get_contents('json_file'));

    unset($days[0]);


    $include_variable = '';
    foreach($days as $day){
        $include_variable  .= <<<EOD
            <tr>
            <td>$day[0]</td>
            <td>$day[1]</td>
            <td>$day[2]</td>
            </tr>
            EOD;
    }

    $str = <<<EOD
        <table class="table">
        <thead>
        <tr>
        <th> Title </th>
        <th>Content</th>
        <th>Date</th>
        </tr>
        </thead>
        <tbody>
        $include_variable 
        </tbody>
        </table>
    EOD;

    return $str;
}

Your Answer

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

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