You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP短代码开发疑问:如何在return中整合foreach循环

解决WordPress短代码中foreach循环整合到return的问题

问题概述

开发一个WordPress短代码用于插入表格,需将所有逻辑封装在dataTypeAllowed函数中通过add_shortcode('data_allowed', 'dataTypeAllowed');调用,但在整合foreach循环到return语句时遇到问题,修改后仅返回表格表头。

错误尝试1:直接在return中嵌入foreach

直接将foreach循环拼接在return的字符串中,触发语法错误:

// Data Types Array
$data_types_array = array( // the order: name, common reference, slug, ACF value, ACF label
    array('Personally Identifiable Information', 'PII', 'pii', $pii['value'], $pii['label']), 
    array('Protected Health Information', 'PHI', 'phi', $phi['value'], $phi['label']),
);

function dataTypeAllowed() {
    return '<table>
                <tr>
                    <th>Permission</th><th>Data Type</th><th>Common Reference</th>
                </tr>' .
                foreach($data_types_array as $data_type){
            echo '<tr>
                    <td' . $small_center . '>' . 
                        (($data_type[3] == 1) ? $allowed : '') . 
                        (($data_type[3] > 1 ) ? $questionable : '') . 
                        (($data_type[3] == 0) ? $not_allowed : '') . 
                    '</td>
                    <td> <a href="data-type/'. $data_type[2] . '">' . $data_type[0] . '</a>' .
                        (($data_type[3] > 1 ) ? '<br> <span style="font-size:11px">' . $data_type[4] . '</span>' : '') .
                    '</td>
                    <td>' . $data_type[1] . '</td>
                </tr>'; } . 
                '</table>';
}
add_shortcode('data_allowed', 'dataTypeAllowed');

错误尝试2:将foreach赋值给变量再嵌入return

试图把foreach循环赋值给变量后拼接,同样触发语法错误:

$foreach_data = foreach($data_types_array as $data_type){
            echo '<tr>
                    <td' . $small_center . '>' . 
                        (($data_type[3] == 1) ? $allowed : '') . 
                        (($data_type[3] > 1 ) ? $questionable : '') . 
                        (($data_type[3] == 0) ? $not_allowed : '') . 
                    '</td>
                    <td> <a href="data-type/'. $data_type[2] . '">' . $data_type[0] . '</a>' .
                        (($data_type[3] > 1 ) ? '<br> <span style="font-size:11px">' . $data_type[4] . '</span>' : '') .
                    '</td>
                    <td>' . $data_type[1] . '</td>
                </tr>'; };

function dataTypeAllowed() {
    return '<table>
                <tr>
                    <th>Permission</th><th>Data Type</th><th>Common Reference</th>
                </tr>' .
                    $foreach_data
                 . 
                '</table>';
}
add_shortcode('data_allowed', 'dataTypeAllowed');

修改后仅返回表头的代码

调整写法后仅显示表头,无循环内容:

$allowed = '<img';
$not_allowed = 'img';
$questionable = 'img';

$data_types_array = array( // the order: name, common reference, slug, ACF value, ACF label
        array('Personally Identifiable Information', 'PII', 'pii', $pii['value'], $pii['label']), 
        array('Protected Health Information', 'PHI', 'phi', $phi['value'], $phi['label']));

function dataTypeAllowed(){
    $response = "";
    $response .= "<table>
        <tr>
            <th>Permission</th><th>Data Type</th><th>Common Reference</th>
        </tr>";
    
    foreach ($data_types_array as $data_type) {
        $response .= "<tr><td  align='center' width='60px' >";
        $response .= ($data_type[3] == 1) ? $allowed : '';
        $response .= ($data_type[3] > 1) ? $questionable : '';
        $response .= ($data_type[3] == 0) ? $not_allowed : '';
        $response .= "</td><td> <a href='data-type/'. $data_type[2] . ''>  $data_type[0] </a>";
        $response .= ($data_type[3] > 1) ? "<br> <span style='font-size:11px'> $data_type[4] </span>" : '';
        $response .= "</td><td> $data_type[1] </td> </tr>";
    }
    $response .= "</table>";
    return $response;
}
add_shortcode('data_allowed', 'dataTypeAllowed');

问题原因

  1. 变量作用域问题:$data_types_array、$allowed等变量定义在函数外部,函数内部无法直接访问,导致foreach循环未执行。
  2. 字符串拼接错误:双引号字符串中使用. $data_type[2] .的拼接方式不符合语法,导致内容生成失败。
  3. HTML标签不完整:$allowed等变量仅定义了<img片段,会导致HTML结构无效。

正确代码实现

将所有依赖变量移入函数内部,修正字符串拼接逻辑,补全HTML结构:

function dataTypeAllowed(){
    // 补全状态图标HTML(替换为实际图标路径)
    $allowed = '&lt;img src=&quot;/path/to/allowed-icon.png&quot; alt=&quot;Allowed&quot; width=&quot;20&quot; height=&quot;20&quot; /&gt;';
    $not_allowed = '&lt;img src=&quot;/path/to/not-allowed-icon.png&quot; alt=&quot;Not Allowed&quot; width=&quot;20&quot; height=&quot;20&quot; /&gt;';
    $questionable = '&lt;img src=&quot;/path/to/questionable-icon.png&quot; alt=&quot;Questionable&quot; width=&quot;20&quot; height=&quot;20&quot; /&gt;';

    // 获取ACF字段值(替换为你的实际字段名)
    $pii = get_field('pii_permission');
    $phi = get_field('phi_permission');

    // 数据类型数组
    $data_types_array = array( 
        array('Personally Identifiable Information', 'PII', 'pii', $pii['value'], $pii['label']), 
        array('Protected Health Information', 'PHI', 'phi', $phi['value'], $phi['label'])
    );

    $response = "&lt;table border='1' cellpadding='8' cellspacing='0'&gt;
        &lt;tr&gt;
            &lt;th&gt;Permission&lt;/th&gt;&lt;th&gt;Data Type&lt;/th&gt;&lt;th&gt;Common Reference&lt;/th&gt;
        &lt;/tr&gt;";
    
    foreach ($data_types_array as $data_type) {
        $response .= "&lt;tr&gt;&lt;td align='center' width='60px'&gt;";
        // 根据ACF值判断显示对应状态
        if($data_type[3] == 1){
            $response .= $allowed;
        } elseif($data_type[3] > 1){
            $response .= $questionable;
        } else {
            $response .= $not_allowed;
        }
        // 正确使用变量插值生成链接
        $response .= "&lt;/td&gt;&lt;td&gt;&lt;a href='data-type/{$data_type[2]}'&gt;{$data_type[0]}&lt;/a&gt;";
        // 当值大于1时显示额外标签
        if($data_type[3] > 1){
            $response .= "&lt;br&gt;&lt;span style='font-size:11px'&gt;{$data_type[4]}&lt;/span&gt;";
        }
        $response .= "&lt;/td&gt;&lt;td&gt;{$data_type[1]}&lt;/td&gt;&lt;/tr&gt;";
    }
    $response .= "&lt;/table&gt;";
    return $response;
}
add_shortcode('data_allowed', 'dataTypeAllowed');

关键修改点

  • 将所有依赖变量移入函数内部,确保函数能正常访问数据。
  • 使用{$变量名}的变量插值语法替代错误的字符串拼接,保证链接等内容正确生成。
  • 补全img标签的完整结构,确保HTML有效性。
  • 改用if-else结构替代多层三元运算符,提升代码可读性。

内容的提问来源于stack exchange,提问作者ashueyUTK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 19:09:31