WordPress短代码PHP文件出现unexpected 'frame'语法错误如何解决?
问题原因
你遇到的语法错误是因为PHP用单引号'包裹整个返回的HTML字符串时,内嵌JavaScript里的单引号(比如getElementById('frame')中的')会被PHP识别为字符串终止标记,直接截断了原返回字符串,因此抛出unexpected 'frame' (T_STRING)错误。
解决方案1:转义字符串内的单引号
在PHP单引号字符串中,要输出原生单引号需要加反斜杠\转义,你只需要把所有JS代码里的单引号全部转义即可:
<?php function torque_hello_world_shortcode() { return '<div class="description pagecontent simple"></div> <a onclick="document.getElementById(\'frame\').style.display = document.getElementById(\'frame\').style.display == \'none\' ? \'block\' : \'none\'; return false;"><img class="someclass" src="#" alt="alt text" style="width:60px;height:60px;cursor:pointer !important;"> <p class="something" style="cursor:pointer !important;">text! <span class="otherclass" style="cursor:pointer !important;">more text</span></p></a> <div class="description pagecontent simple"></div>'; } add_shortcode( 'helloworld', 'torque_hello_world_shortcode' );
解决方案2:使用Nowdoc语法(更推荐)
如果需要拼接大段含多类型引号的HTML/JS代码,推荐使用PHP Nowdoc语法,无需对任何引号做转义,代码可读性更高:
<?php function torque_hello_world_shortcode() { // Nowdoc标识符可以自定义,只要前后一致、结束标识符顶格写即可 $html = <<<'HTML_CONTENT' <div class="description pagecontent simple"></div> <a onclick="document.getElementById('frame').style.display = document.getElementById('frame').style.display == 'none' ? 'block' : 'none'; return false;"><img class="someclass" src="#" alt="alt text" style="width:60px;height:60px;cursor:pointer !important;"> <p class="something" style="cursor:pointer !important;">text! <span class="otherclass" style="cursor:pointer !important;">more text</span></p></a> <div class="description pagecontent simple"></div> HTML_CONTENT; return $html; } add_shortcode( 'helloworld', 'torque_hello_world_shortcode' );
可选优化建议
如果后续需要维护代码,可以考虑把行内onclick事件抽离为单独的JS方法绑定,避免HTML、JS、PHP三层混写带来的转义维护成本。
内容的提问来源于stack exchange,提问作者bagarangmeetsruffio
相关产品推荐
相关产品推荐

