WordPress短代码PHP文件语法错误



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

我有一个PHP返回语句,其中包括HTML。在HTML中,我有一个javascript onclick函数。Visual Studio Code抛出一个语法错误,这是,意外的'frame' (T_STRING),期望','或';'

我读过其他关于堆栈溢出的文章,我试过转义字符串内的单引号,但我可能会不准确地转义。下面是一些没有转义的原始代码:

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

<?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行,您基本上关闭字符串并在其后面加上单词"frame",而不使用连接甚至$ variable符号)。

如果你用单引号打开一个字符串,第二个单引号将关闭字符串。如果需要在中使用单引号你的字符串,你需要转义它,用反斜杠: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' );

最新更新