首页 > 解决方案 > WordPress 简码 PHP 文件中的语法错误

问题描述

我正在尝试注册一个 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' );

标签: phpwordpressshortcode

解决方案


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

如果您用单引号打开一个字符串,第二个单引号将关闭该字符串。如果您需要字符串中使用单引号,则需要使用反斜杠对其进行转义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' );

推荐阅读