【问题标题】:Syntax error in WordPress shortcode PHP fileWordPress 简码 PHP 文件中的语法错误
【发布时间】:2021-10-17 15:37:29
【问题描述】:

我正在尝试注册 WordPress 短代码。

我有一个包含 HTML 的 PHP 返回语句。在 HTML 中,我有一个 javascript onclick 函数。 Visual Studio Code 抛出语法错误,即意外的“帧”(T_STRING),需要“,”或“;”

我已阅读有关 Stack Overflow 的其他文章,并尝试转义字符串内的单引号,但我可能会不准确地转义。下面是一些没有任何转义的原始代码。

我知道下面的代码可能不漂亮,但仍然感谢所有帮助。

<?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' );

【问题讨论】:

    标签: php wordpress shortcode


    【解决方案1】:

    您在 return 语句中混合了单引号和双引号(在字符串的第 2 行,您基本上关闭了字符串并在其后面加上单词“frame”,不使用连接,甚至不使用 $ 变量符号)。

    如果您用单引号打开一个字符串,第二个单引号将关闭该字符串。如果你需要在你的字符串使用单引号,你需要escape它,用反斜杠:echo 'Arnold once said: "I\'ll be back"';
    我在您的代码中添加了反斜杠:

    <?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' );
    

    【讨论】:

    • 谢谢。一切正常。你能告诉我为什么在这个字符串中你不需要转义最后一个“回声”阿诺德曾经说过:“我会回来(为什么不转义这个”)';
    • 因为这是结束语。字符串有一个开始和结束引号,总是相同的类型(单引号或双引号)。如果您使用单引号打开和关闭字符串,则可以在其中使用双引号而无需转义(反之亦然)。如果您使用单引号打开和关闭,并且需要在其中使用单引号,则需要使用反斜杠对其进行转义。
    猜你喜欢
    • 2014-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多