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

Visual Composer插件开发:如何将HTML嵌入PHP短代码?求助报错

嘿,我帮你找出问题啦!你这段代码触发致命错误是因为HTML语法有明显的问题,咱们来一步步修复:

问题根源

你写的错误代码里有两处关键的HTML语法问题:

  • 错误的标签写法:< class=\"learn-more\"> 这里漏掉了标签名!看后面的闭合标签是</button>,所以这里应该是 <button class=\"learn-more\">
  • 不完整的标签直接导致了语法解析失败,触发了致命错误
修复后的完整代码
public function renderMyBartag( $atts, $content = null ) {
    extract( shortcode_atts( array(
        'foo' => 'something',
        'color' => '#FF0000'
    ), $atts ) );
    
    $content = wpb_js_remove_wpautop($content, true); // 修复$content中未闭合/多余的段落标签
    
    $output = "<div class=\"container\">
        <button class=\"learn-more\">
            <div class=\"circle\">
                <span class=\"icon arrow\"></span>
            </div>
            <p class=\"button-text\">{$foo}</p>
        </button>
    </div>";
    
    return $output;
}
额外的优化建议

为了以后更不容易出错,给你几个小技巧:

  • 写嵌套HTML时尽量格式化代码(换行、缩进),这样一眼就能看出标签是否匹配、有没有语法错误
  • 如果你觉得转义双引号麻烦,可以用单引号包裹外层字符串,内部双引号就不用转义了,代码更清爽:
$output = '<div class="container">
    <button class="learn-more">
        <div class="circle">
            <span class="icon arrow"></span>
        </div>
        <p class="button-text">' . $foo . '</p>
    </button>
</div>';
  • 还可以用PHP的HEREDOC语法,支持直接在字符串里解析变量,可读性拉满:
$output = <<<HTML
<div class="container">
    <button class="learn-more">
        <div class="circle">
            <span class="icon arrow"></span>
        </div>
        <p class="button-text">{$foo}</p>
    </button>
</div>
HTML;

这样修改后,代码应该就能正常运行啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:27:45