最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Shortcode called twice

programmeradmin1浏览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')

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')
Share Improve this question asked Oct 15, 2019 at 15:08 pull-linkpull-link 133 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 5

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');

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论