0

I'm working on my product information using a shortcode who automatically can generate a table with information. But it looks like the shortcode gets called twice. I'm not a great back-end developer but I'm trying to learn some basics so I can make some basic PHP functions. I would really appreciate some help. Thanks in advance.

My code looks like this:

function displayTable()
{
    echo '<table>';
    echo '<tbody>';
    $fields = get_field_objects();
    foreach($fields as $field)
    {
      echo '<td>';
      echo '<td>'. $field['label'] .'</td>';
      echo '<td>'. $field['value'] .'</td>';
      echo '</tr>';
    }
    echo '</tbody>';
    echo '</table>';
}
add_shortcode('popnagel-tabel', 'displayTable')

1 Answer 1

4

Shortcodes should never echo; they should always return the text to be displayed. See the User Contributed Notes in the add_shortcode() docs.

Your code should read more like this:

function displayTable() {
    $string = '';
    $string .=  '<table>';
    $string .=  '<tbody>';
    $fields = get_field_objects();
    foreach($fields as $field)
    {
      $string .=  '<td>';
      $string .=  '<td>'. $field['label'] .'</td>';
      $string .=  '<td>'. $field['value'] .'</td>';
      $string .=  '</tr>';
    }
    $string .=  '</tbody>';
    $string .=  '</table>';
    return $string;
}
add_shortcode('popnagel-tabel', 'displayTable');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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