WordPress短码始终显示在页面顶部,如何使其在文章任意位置显示?
WordPress短码显示在页面顶部的问题修复
问题根源
WordPress短码的工作逻辑是:解析短码时,会收集短码函数的返回值,再将这个值插入到短码在文章中的对应位置。而你的代码里直接用echo输出内容,这会绕过WordPress的短码输出流程,内容会被直接发送到浏览器,所以会出现在页面最顶部,而非短码所在位置。
修复方案
- 将所有
echo语句改为拼接字符串,最后返回拼接好的内容,而非直接输出。 - 修改短码主函数
main,让它接收子函数的返回值,再统一返回给WordPress的短码解析器。
修改后的代码
1. 调整getLotoSecond函数
function getLotoSecond() { $html = file_get_contents_curl('URL__ADDRESS'); // 提取目标列表片段 $start = stripos($html, '<ul id="results-2" class="results-items">'); $end = stripos($html, '</ul>', $offset = $start); $length = $end - $start; $list = substr($html, $start, $length); // 匹配数字内容 preg_match_all('(<label for="LotoPart_C2_([1-6]|Additional)">([0-9]|[1-9][0-9])</label>)', $list, $matches); $items = $matches[2]; // 拼接输出字符串(替代原echo) $output = '<ul>'; for($i = 0; $i < 7; $i++) { if($i == 6) { $output .= '<li style="width:30px;height:30px;border-radius:5px;background-color:#F4A024;color:white;font-size:20px;text-align:center;line-height:30px;display:inline-block;margin:0px 5px 5px 0px;">' . $items[$i] . '</li>'; } else { $output .= '<li style="width:30px;height:30px;border-radius:5px;background-color:#294A70;color:white;font-size:20px;text-align:center;line-height:30px;display:inline-block;margin:0px 5px 5px 0px;">' . $items[$i] . '</li>'; } } $output .= '</ul>'; // 返回拼接好的内容 return $output; }
2. 调整短码主函数main
function main($atts) { $output = ''; if($atts["type"] == "loto-prvy") { $output = getLotoFirst(); // 注意:getLotoFirst函数也需要做同样的修改,改为返回字符串 } else if($atts["type"] == "loto-druhy") { $output = getLotoSecond(); } // 返回最终内容给短码解析器 return $output; } add_shortcode('tipo', 'main');
补充说明
如果getLotoFirst函数的结构和getLotoSecond一致,也需要按照同样的逻辑修改——把所有echo替换为字符串拼接,最后返回结果。
内容的提问来源于stack exchange,提问作者Forlis
相关产品推荐
相关产品推荐

