
wordpress短代码若直接使用echo输出,会导致内容被提前发送到响应流开头,从而强制显示在页面顶部;正确做法是通过输出缓冲(ob_start)捕获并返回内容,确保其精准插入到编辑器中指定位置。
wordpress短代码若直接使用echo输出,会导致内容被提前发送到响应流开头,从而强制显示在页面顶部;正确做法是通过输出缓冲(ob_start)捕获并返回内容,确保其精准插入到编辑器中指定位置。
在WordPress插件开发中,短代码(shortcode)的核心契约是:必须返回字符串,绝不能直接输出(echo/print)。一旦函数内部调用 echo 或 print,PHP会立即将内容写入HTTP响应缓冲区——此时WordPress尚未开始渲染正文,因此你的HTML会被“挤”到整个页面最前端(即之前或开头),完全脱离编辑器中 shortcode 所在的逻辑位置。
你当前的 getLotoSecond() 函数正是问题根源:它直接 echo 了 <ul></ul> 列表,而非返回字符串。即使将其封装在 main() 中,也无法改变输出时机。
✅ 正确解决方案:使用输出缓冲(Output Buffering)
将 main() 短代码回调函数重构为缓冲模式,确保所有子函数的“视觉输出”被暂存、捕获,并最终作为返回值交由WordPress注入到正确DOM位置:
function main($atts) {
ob_start(); // 启动输出缓冲
if (isset($atts['type']) && $atts['type'] === 'loto-prvy') {
getLotoFirst();
} elseif (isset($atts['type']) && $atts['type'] === 'loto-druhy') {
getLotoSecond();
}
return ob_get_clean(); // 获取并清空缓冲区内容,返回字符串
}
add_shortcode('tipo', 'main');⚠️ 同时,请务必同步修改 getLotoSecond()(及 getLotoFirst())函数:将所有 echo 替换为字符串拼接 + return,或保留 echo 但依赖上述缓冲机制(推荐后者以最小化改动)。例如优化后的 getLotoSecond() 应保持原逻辑,仅移除 echo 改为构建 $output 并 return(更佳实践):
function getLotoSecond() {
$html = file_get_contents_curl('URL__ADDRESS');
$start = stripos($html, '<ul id="results-2" class="results-items">');
if ($start === false) return ''; // 安全兜底
$end = stripos($html, '</ul>', $start);
if ($end === false) return '';
$list = substr($html, $start, $end - $start);
preg_match_all('/<label for="LotoPart_C2_([1-6]|Additional)">([0-9]|[1-9][0-9])<\/label>/', $list, $matches);
$items = $matches[2];
$output = '<ul>';
for ($i = 0; $i < min(7, count($items)); $i++) {
$bg = ($i === 6) ? '#F4A024' : '#294A70';
$output .= sprintf(
'<li style="width:30px;height:30px;border-radius:5px;background-color:%s;color:white;font-size:20px;text-align:center;line-height:30px;display:inline-block;margin:0 5px 5px 0;">%s</li>',
esc_attr($bg),
esc_html($items[$i])
);
}
$output .= '</ul>';
return $output; // 关键:返回而非echo
}? 关键注意事项:
- 始终对用户数据(如
$items[$i])执行esc_html()过滤,防止XSS; - 使用
isset()检查$atts['type'],避免未定义索引警告; - 添加
stripos失败判断,提升健壮性; - 避免硬编码URL,应使用
wp_remote_get()替代file_get_contents_curl()(更安全、支持超时/重试); - 短代码函数名建议语义化(如
tipo_shortcode_handler),便于维护。
遵循此模式,你的 [tipo type="loto-druhy"] 将严格按编辑器光标位置渲染,彻底解决“总在顶部”的问题。


















